Check given number is palindrome using java (non-recursive/example)

What is palindrome ?

  • A palindrome is a word, number, phrase, or other sequence of characters which reads the same from backward or forward direction.
  • Palindromic number is a number whose digits, with decimal representation are the same read backward.
  • For example:
  • We will use iterative or non recursive algorithm to check given number is palindrome.

Examples of palindromic & non-palindromic numbers:

S. No. Input number Reverse(input number) isPalindrome
1 1234 4321 No
2 12321 12321 Yes
3 4554 4554 Yes
4 569 965 No

Algorithm: check given input number is palindrome

  1. Read input number from console.
  2. Reverse given input number.
  3. Compare given number equals reversed number.
    1. If reverse number is equal to given number then number is palindrome.
    2. else, given number is not palindrome.

Program: check given integer is palindromic number using java

package org.learn;

import java.util.Scanner;

public class PalindromeNumber {
 public static void main(String[] args) {
  try (Scanner scanner = new Scanner(System.in)) {

   System.out.printf("Enter input number : ");
   int inputNumber = scanner.nextInt();
   int reverseNumber = reverseNumber(inputNumber);
   if(inputNumber == reverseNumber)
   {
    System.out.printf("Input number = %d is palindrome",inputNumber);
   } else {
    System.out.printf("Input number = %d is not a palindrome",inputNumber);
   }
  }
 }

 private static int reverseNumber(int inputNumber) {
  int reverseNumber = 0;
  int digit = 0;
  while (inputNumber > 0) {
   // get last digit e.g. 123 % 10 = 3
   digit = inputNumber % 10;

   // after every loop get the next number
   // which is at 10 place from current number.
   reverseNumber = reverseNumber * 10 + digit;
   inputNumber /= 10;
  }
  return reverseNumber;
 }
}

Ouput: check given integer is palindrome number using java

Enter input number : 1221
Input number = 1221 is palindrome

Enter input number : 12345
Input number = 12345 is not a palindrome
Scroll to Top