← Back to Leo Academy Masterclass

Problem #9: Palindrome Number

Easy Math

Intuition & Strategy Breakdown

Revert the second half of the number by extracting digits from the back. Compare the reversed half with the remaining first half. Negative numbers and numbers ending in 0 (except 0 itself) are not palindromes.

Python Solution

class Solution:
    def isPalindrome(self, x: int) -> bool:
        # Edge Case: Negatives and numbers ending in 0 (except 0 itself)
        if x < 0 or (x % 10 == 0 and x != 0):
            return False
        
        rev = 0
        # Only reverse half of the number
        while x > rev:
            rev = rev * 10 + x % 10
            x //= 10
        
        # Check even (x == rev) or odd (x == rev // 10)
        return x == rev or x == rev // 10

Java Solution

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
        int rev = 0;
        while (x > rev) {
            rev = rev * 10 + x % 10;
            x /= 10;
        }
        return x == rev || x == rev / 10;
    }
}
Watch Interactive Video on Leo Academy Main App