SDE & MLE Prep

9. Palindrome Number

Problem

Decide whether the integer x reads the same forwards and backwards.

Example: 121 → true; -121 → false; 10 → false

Constraints: follow-up: without converting to a string.

Negative numbers and numbers ending in 0 (except 0) aren't palindromes. Reverse only the second half of the digits and compare with the first half — no overflow risk.

Complexity: O(log x).

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0 or (x % 10 == 0 and x != 0):
            return False
        rev = 0
        while x > rev:
            x, d = divmod(x, 10)
            rev = rev * 10 + d
        return x == rev or x == rev // 10