Saturday, October 11, 2014

Check if a number is palindrome

A Palindrome number is a number which remains the same when its digits are reversed.

         if (number == reverse(number)){
            //number is palindrome
        } 

121, 1, 22 etc are palindrome numbers. In this post, I have discussed how to reverse a number. But, there could be an issue with the approach. Let's take below case:

In Java highest integer is, i.e. Integer.MAX_VALUE = 2147483647
Now, what if you try to reverse above number?

Reversed (i.e. 7463847412 ) number can't fit in an integer and hence it will overflow. One alternative is; store the value in a long and then reverse it. This approach will work but it's not a very cleaner and cooler way.
Let's figure out a different approach?

Algorithm

We can apply the more fundamental approach of comparing the first and last digits and if they are equal move to second and second last digits and so on. Keep doing it until the comparison fails or the number reduces to a single digit. This approach is followed to check if a string is palindrome. This approach doesn't have space overhead ( except two temporary variables to get left most and the right most digit). 

         number = 121   
         leftMostDigit = 1
         rightMostDigit = 1
         leftMostDigit == rightMostDigit
         so number = 2 

Implementation

Recursive implementation in Java. Each recursive call trims the right most and left most digit of the number.

          So 12321 will become 232 in the second call.

     /**  
       * Recursive method to check if a number is palindrome  
       *   
       * @param number  
       * @return true/false  
       */  
      public static boolean isPalindrome(int number){  
           System.out.println(" number is :"+ number);  
           if(number < 0){  
                isPalindrome(-number);  
           }  
           if(number < 10){  
                return true; //single letter number is always palindrome  
           }  
           int rightMostDigit = number % 10;  
           int leftMostDigit = number;  
           int factor = 1;  
           while(leftMostDigit >= 10 ){  
                leftMostDigit = leftMostDigit / 10;  
                factor = factor * 10;  
           }  
           if(leftMostDigit != rightMostDigit){  
                return false;                 
           }  
           number = number % factor; //remove left most number  
           number = number / 10; // remove right most number  
           return isPalindrome(number);  
      }  

--
keep coding !!!

No comments:

Post a Comment