Check Palindrome Number Program in Java

What is Palindrome Number?

A Palindrome Number is a number that even when reversed is same as original number
Examples of Palindrome Number
121, 393, 34043, 111, 555, 48084 
Examples of Palindrome Number
 LOL, MADAM
Program Logic
  • Fetch the input number that needs to be checked for being a Palindrome
  • Copy number into a temporary variable and reverse it.
  • Compare the reversed and original number.
  • If they are same, number is "palindrome number"
  • Else number is not "palindrome number"

Program to check whether input number is palindrome or not

  1. package com.guru99;
  2. public class PalindromeNum {
  3. public static void main(String[] args)
  4. {
  5. int lastDigit,sum=0,a;
  6. int inputNumber=171; //It is the number to be checked for palindrome
  7. a=inputNumber;
  8. // Code to reverse a number
  9. while(a>0)
  10. { System.out.println("Input Number "+a);
  11. lastDigit=a%10; //getting remainder
  12. System.out.println("Last Digit "+lastDigit);
  13. System.out.println("Digit "+lastDigit+ " was added to sum "+(sum*10));
  14. sum=(sum*10)+lastDigit;
  15. a=a/10;
  16. }
  17. // if given number equal to sum than number is palindrome otherwise not palindrome
  18. if(sum==inputNumber)
  19. System.out.println("Number is palindrome ");
  20. else
  21. System.out.println("Number is not palindrome");
  22. }
  23. }

Output:

Input Number 171
Last Digit 1
Digit 1 was added to sum 0
Input Number 17
Last Digit 7
Digit 7 was added to sum 10
Input Number 1
Last Digit 1
Digit 1 was added to sum 170
Number is palindrome

No comments:

Post a Comment