January 20, 2019

9. Palindrome Number

9. Palindrome Number

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        // run test cases:
        // 1, 10, 100, 121, 12321, 1000021
        int digit = 1;
        int temp = x;
        while (temp >= 10) {
            temp /= 10;
            digit *= 10;
        }
        
        while (x > 0) {
            int lastDigit = x % 10;
            int firstDigit = x / digit;
            if (lastDigit != firstDigit) {
                return false;
            }
            x %= digit;
            x /= 10;
            digit /= 100;
        }
        
        return true;
    }
}
comments powered by Disqus