To Reverse a given Number in Java
TO Reverse a Given Number in Java
- we take an Integer to store the given number.
- After we have to take a try & catch block. If try block consists a error occuring statement is in this block.
- Then that statement must be catched by catch block and print the error occurred because of try & catch block.
- According to that While loop it is repeatedly revolving around the loop until the condition is false (or) not true.
- In this While loop
5.2 Next we have to store the temp variable in to another variable because we have to number is we are getting from that temp variable.
5.3 Every repetation of loop execution temp stores the remainder variable then sum = sum * 10 + temp; it tells about the every temp variable is stored in sum.
5.4 The sum variable is multiplied by 10 because every remainder must be multiplied and added the variable to sum.(temp storing the remainder ).
5.5 At the same time we have to reduce the given number by writing the statement n=n/10;
that statement stores the Quotient so it reduces the number by again intialize that "n" in to "n" by itself.
public class ReverseNum {
public static void main(String[] args) {
System.out.println("Enter a Number");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m;
m = n;
int sum = 0;
try {
while (n > 0) {
int temp = n % 10;
sum = sum * 10 + temp;
n = n / 10;
}
System.out.println("The number is" + sum);
if(sum==m)
{
System.out.println("The Number is polindrome");
}
else
{
System.out.println("It is not a polindeome");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
0 comments:
Post a Comment