Palindrome Number

Reverse the lower half — equals (or with-middle-digit equals) the upper half.

Easy
Time O(log n) Space O(1)
LeetCode
3 min read
math

Problem#

Return true iff x reads the same forward and backward. Negative numbers are never palindromes.

Examples#

  • 121true.
  • -121false; 10false.

Constraints#

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

Approach#

Negatives and non-zero numbers ending in 0 are out. Otherwise, build the reverse of the right half by repeatedly peeling digits, stopping once reversed >= remaining left half. Palindrome iff left == reversed (even length) or left == reversed / 10 (odd length).

Solution#

Palindrome Number
class Solution {
public:
bool 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;
}
};

Editorial#

Reversing only the lower half avoids overflow even for INT_MAX — we never need to fit the full reversed number into an int. The loop terminates exactly when we’ve consumed half the digits.

Complexity#

  • Time: O(log10 n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.