Tuesday, February 23, 2016

[LeetCode] 9. Palindrome Number











1. Wrong code. 1000021 --> true. Once 1000000 and 1 is subtract, only 2 left.
Should get the number of digits first.

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


No comments:

Post a Comment