InterviewPrepKit

Home / Coding / Math & Geometry

Palindrome Number

easy Original β†—
Solving tips
  • Handle the quick rejects: negatives are never palindromes, and any positive number ending in 0 (except 0) can't be one.
  • Reverse arithmetically with rev = rev*10 + x%10 and x //= 10; no string conversion needed.
  • Best trick: reverse only the second half, stopping when x <= rev, which also avoids overflow in fixed-width languages.
  • For odd digit counts, compare x against rev // 10 to drop the middle digit; target O(log10 x) time, O(1) space.

Problem

Given an integer x, return True if x reads the same forwards and backwards, and False otherwise. A negative number is never a palindrome because the leading minus sign has no trailing counterpart. Aim to solve it without converting the number to a string.

Examples

  • x = 121 β†’ True β€” reversing the digits gives 121.
  • x = -121 β†’ False β€” reversed it reads 121-, which differs from -121.
  • x = 10 β†’ False β€” reversed it reads 01, i.e. 1, which differs from 10.

Constraints

  • -2^31 <= x <= 2^31 - 1

Think about it first

Hint 1 Negatives are out immediately. Also, any positive number ending in `0` (except `0` itself) cannot be a palindrome, because a palindrome cannot start with `0`.
Hint 2 You can rebuild the number reversed using arithmetic only: repeatedly peel the last digit with `% 10` and append it to a running reversed value with `rev = rev * 10 + digit`.
Hint 3 You don't have to reverse the whole number β€” reverse only the second half and compare it to the first half. Stop when the remaining "first half" is no larger than the reversed "second half." For odd digit counts, drop the middle digit with `rev // 10`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.