By definition a number is said to be palindrome,if the reverse of the number is equal to the same original number.i.e we need to find the reverse of the given number and we should check it with original number.This is little complicated than strings because for strings we can use some built in functions to reverse the string.As we have done it in sum of digits to get the last digits of the number using the number 10. We need to implement the same logic over here such that we get the last element and make get the reverse of the given number.

Let us go deep into the logic first we shall get the last digit of the number and then multiply the obtained digit such that we get the reverse of the number.Now, we shall trace out the program manually and then we shall write the program for his. The main logic is

reverse=0; while(n>0) { rem=n%10; n=n/10; reverse=reverse*10+rem; }

Here rem defined for remainder or to get the last digit,n for storing the given number,reverse for storing the reverse number, but initial we should reverse to zero.Let us give 141 as input for n.

1.For the first iteration of loop the value of n will be 141 and it can enter the while loop.We get the remainder as 1 and 14 as next n value and value of the reverse will be 1.

2.For the second iteration of the loop the value of n will be 14 and it can enter the while loop.We get the remainder as 4 and 1 as next n value and value of the reverse will be 14.

3.For the third iteration of the loop the value of n is 1 and it enters the while and remainder will be 1 and the n value will be 0.Therefore the value of the reverse will be (14*10)+1=140+1=141.

4.The fourth iteration will be failed since the n value will be 0.

Let us convert this in to the program:

class palindrome { public static void main(String arg[]) { System.out.print("Enter to a value to find palindrome or not:"); Scanner ob=new Scanner(System.in); int n=ob.nextInt(); int temp=n; int rem,reverse=0; while(temp>0) { rem=temp%10; temp=temp/10; reverse=reverse*10+rem; } //end of while loop if(reverse==n) System.out.print("Given number is palindorme:"); else System.out.prin("Given number is not paindrome:"); }//end of main method }//end of class

**Output:
You can also download the program**

**
Advertisements
**

Pingback: Java program to check Armstrong number | letusprogram….!!!