Write java program to check if a number is palindrome in Java?

A number that does not change on reversing is called a palindrome number. In other words, when reversing the digits of a number does not affect the number is called the palindrome number. For example, 121, 343, 555, 606, 999, 1001, 1331 are the palindrome numbers. In this section, we will create a Java program to check the number is palindrome or not.

Algorithm to Find Palindrome Number

  • Get the number, which is going to be checked for palindrome.
  • Create a copy of the number by storing it in some temporary variable.
  • Now, reverse the number.
  • Check with the copy whether the reversed number is equal or not.
  • If it is equal, then we have a palindrome number.
  • Otherwise, the number is not a palindrome.

The following Java program demonstrates how to check a given number is a palindrome number or not by using a while loop.

Iterative Approach

Filename: PalindromeNumberExample.java


Explanation: We have used a Java while loop to reverse the number. The number of iterations of the while loop depends on the number of digits present in the given number. In our case, it is 3. Let’s see the working of the program.

First Iteration: sum = sum * 10. However, we have initialized the value of sum as 0; Therefore, we get sum = 0 * 10 = 0. Again, we update the value of sum by adding the remainder we get by dividing the given number (535). Thus, we get sum = 0 + (535 % 10). sum = 0 + 5 = 5. Finally, we divide the given number by 10 and assign the quotient to the number. no = 535 / 10 = 53. The updated value of no variable is 53 which is to be used in the next iteration.

Second Iteration: In the second iteration, the value of sum is 5. Hence, sum = 5 * 10 = 50. Again, we add the remainder. This time the number is 53. Hence, we have sum = 50 + (53 % 10). sum becomes 50 + 3 = 53. At last, the given number shrink again by one digit and becomes 5. no = 53 / 10 = 5.

Third Iteration: The process is similar. The sum is 53. Therefore, sum = 53 * 10 = 530. After adding the remainder, we get 535. Also, the number becomes no = 5/10 = 0. Since every time we have checked the while loop condition. When the condition no>0 returns false, the loop terminates.

Recursive Approach

We can also check the palindrome number by using the recursive approach.

Filename: PalindromeNumberExample1.java


Explanation: In the recursive approach also, we have created a copy of the number and then compared it with the number that we have reversed. Note that as per mathematical definition, a negative number can never be a palindromic number.

Pin It on Pinterest

Share This