Palindrome Number
EasyTop Interview 150 Math & GeometrytcsBoschCognizantPornHubAccentureSAPProblem
A whole number is a palindrome when its decimal digits read the same from left to right and from right to left.
Given the integer x, return true if it is a palindrome, otherwise false.
Solve it with arithmetic on the digits, without converting the number to a string.
Constraints
- −2³¹ ≤ x ≤ 2³¹ − 1
Examples: pick one to animate
Solutions
Time: Half of the digits are processed, and a number n has about log10(n) digits.
Space: Only x and the reversed half rev are stored.
Negative numbers and numbers ending in 0 (except 0) are never palindromes. For the rest, peel digits off the end of x and push them onto rev until rev is no longer smaller than x. That means we are at the middle. A palindrome has the first half equal to the reversed second half, with an odd middle digit dropped from rev. Reversing only half also avoids overflow.