/** * An example program that check if a number is a palindrome using while loop. */ public class ExampleProgram { public static void main(String[] args) { System.out.println(122 + " is a palindrome? : " + isPalindrome(122)); System.out.println(121 + " is a palindrome? : " + isPalindrome(121)); System.out.println(4555 + " is a palindrome? : " + isPalindrome(4555)); System.out.println(45554 + " is a palindrome? : " + isPalindrome(45554)); } public static boolean isPalindrome(int n) { // compare number with reverse return n == reverse(n); } public static int reverse(int n) { int reversedDigitNumber = 0; while( n > 0) { // extract last digit int digit = n % 10; // shift number and add digit to the right reversedDigitNumber = (reversedDigitNumber * 10) + digit; // remove the digit processed n = n / 10; } return reversedDigitNumber; } }
And doing so will give the output below
122 is a palindrome? : false 121 is a palindrome? : true 4555 is a palindrome? : false 45554 is a palindrome? : true