number is palindrome or not in java

Check whether a number is palindrome or not

Given an input integer as a number, the objective is to check whether or not the given number integer is a Palindrome or not in Java Language. To do so we’ll reverse the the number using the modulo and divide operators and check if the reversed number matches the original number. Here are few methods to Check Whether or Not the Number is a Palindrome in Java Language,

Using Iteration

Using Recursion

number is palindrome or not in java

Check whether a number is palindrome or not Using Iteration

Method 1
/*
 * Author: Zameer Ali
 * */
public class Main
 {
   public static void main (String[]args)
   {
     //variables initialization
     int num = 12021, reverse = 0, rem, temp;

       temp = num;
     //loop to find reverse number
     while (temp != 0)
       {
     	rem = temp % 10;
     	reverse = reverse * 10 + rem;
     	temp /= 10;
       };

     // palindrome if num and reverse are equal
     if (num == reverse)
       System.out.println (num + " is Palindrome");
     else
       System.out.println (num + " is not Palindrome");
   }
 }

Output:

12021 is Palindrome

Check whether a number is palindrome or not Using Recursion

Method 1
/*
 * Author: Zameer Ali
 * */
public class Main
{
  public static void main (String[]args)
  {
    //variables initialization
    int num = 12021, reverse = 0, rem, temp;

    // palindrome if num and reverse are equal
    if (getReverse(num, reverse) == num)
     System.out.println (num + " is Palindrome");
    else
      System.out.println (num + " is not Palindrome");
  }
  
  static int getReverse(int num, int rev){
    if(num == 0)
        return rev;
    
    int rem = num % 10;
    rev = rev * 10 + rem;
    
    return getReverse(num / 10, rev);
}
}

Output:

12021 is Palindrome