Today, we will see how to reverse a number and calculate the sum of all digits. It is a faster way to reverse a number. Because we will use string in this code. So, let's see how it is.............
import java.util.Scanner; //import a package to take input from keyboard
public class ReverseNumberByString //main class
{
public static void main(String[] args) //main method
{
Scanner input = new Scanner(System.in); //create an object of type of Scanner
char []str = new char[50]; //declare an array of char type
char[] reverse = new char[50]; //declare an array of char type
System.out.print("Enter a number to reverse : "); //user is asked to give an input
String num = input.next(); //store the input into a variable type of String
int i=0, len=num.length(), sum = 0; //store the length of the string into len by using length(); method
while(i < len)
{
str[i] = num.charAt(i); //convert the string into char array by charAt(); method
i++;
}
System.out.println();
System.out.print("After reversing : ");
for(int j=len-1,k=0;j>=0;j--,k++)
{
reverse[k]=str[j];
System.out.print(reverse[k]);
sum+=str[j]-(char)48;
}
System.out.println("\n\nSum of all digits : "+sum);
System.out.println();
}
}
save this code and use the name of main class as file name. If you have any problem, feel free to leave a comment.......
0 comments:
Post a Comment