How to check if a number is palindrome in java

A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, generally if used comma, separators or other word dividers are ignored. [Not mandatory]

Similarly, palindrome numbers are those numbers which represent same number if all digits are reversed (Underscores can be ignored in large numbers such as 1_00_00_001). Underscores are new addition in java 7 features.

To verify, if a given number is palindrome is or not, we need to reverse the number and compare with original number if both are equal or not.

Lets write some code to solve this.

package com.howtodoinjava.puzzle;

public class PalindromeTest
{
    /**
     * Test the actual code if it works correctly
     * */
    public static void main(String[] args)
    {
        System.out.println(checkIntegerPalindrome( 100 )); //false
        System.out.println(checkIntegerPalindrome( 101 )); //true
        System.out.println(checkIntegerPalindrome( 500045 )); //false
        System.out.println(checkIntegerPalindrome( 50005 )); //true
    }

    /**
     * This function will test the equality if a number and its reverse.
     * @return true if number is palindrome else false
     * */
    public static boolean checkIntegerPalindrome(int number)
    {
        boolean isPalindrome = false;
        if(number == reverse(number))
        {
            isPalindrome = true;
        }
        return isPalindrome;
    }

    /**
     * This function will reverse a given number.
     * @return reverse number
     * */
    public static int reverse(int number)
    {
        int reverse = 0;
        int remainder = 0;
        do {
            remainder = number % 10;
            reverse = reverse * 10 + remainder;
            number = number / 10;

        } while (number > 0);
        return reverse;
    }
}

Output:

false
true
false
true

If you need to test floating point numbers then only option is to convert them in string and compare the number and its reverse for string equality. Remember to remove period from strings before testing the equality. Also, test the equality using equals() method, and do not use “==” operator.

Happy Learning !!

Lokesh

I have 7 Years of rich experience in java technology. This has only increased my hunger to learn more. In this blog, i will be writing on different topics occasionally, and would love to engage in some meaningful serious discussions with you folks.

You may also like...

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear/post as intended.


Want to ask any question? Or suggest anything?