Sunday, January 4, 2015

9. Palindrome Number Leetcode Java

Determine whether an integer is a palindrome. Do this without extra space.

Solution:
1. Use the reverse Integer to reverse it and check if they are equal. If it overflows during the revers, then it is not a palindrome number. I am not going to provide the code, please refer to reverse Integer.

2.compare the leftmost digit with rightmost digit one by one till the two meets. Calculating rightmost digit is easy just mod 10, while calculating leftmost digit is more advanced. First find the biggest dividend of the number and leftmost digit will be the number divided by the dividend.




    public boolean isPalindrome(int x) {  
     if(x<0) return false;   
     if(x<10) return true;  
     int div=10;  
     while(x/div>=10) div*=10;  
     while(div>0){  
       int l=x/div;  
       int r=x%10;  
       if(l!=r) return false;  
       x=x-l*div;  
       div=div/100;  
       x=x/10;  
     }  
     return true;  
   }  

No comments:

Post a Comment