Palindrome Number
Palindrome Number
Learn how to efficiently check if an integer is a palindrome without converting it to a string, by comparing its first half with its reversed second half.
In depth
A palindrome number reads the same forwards and backward. Determining if an integer is a palindrome efficiently, without string conversion, involves comparing its first half with a reversed version of its second half.
How it Works
Handle Edge Cases
First, identify numbers that cannot be palindromes: negative numbers are never palindromes. Numbers ending in `0` (e.g., `120`) are also not palindromes, unless the number itself is `0`.
Initialize and Iterate
Initialize a `reversed_half` variable to `0`. The core logic involves a `while` loop that continues as long as the original number `x` is greater than `reversed_half`. In each iteration:
1. Extract and Append: The last digit of `x` is extracted (`x % 10`) and appended to `reversed_half`. This is done by multiplying `reversed_half` by `10` and adding the extracted digit. 2. Remove Digit: The last digit is then removed from `x` by integer division (`x //= 10`).
This process effectively builds the reversed second half of the number in `reversed_half` while simultaneously reducing `x` to its first half.
function isPalindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return false
reversed_half = 0
while x > reversed_half:
reversed_half = reversed_half * 10 + x % 10
x = x // 10
return x == reversed_half or x == reversed_half // 10Final Comparison
The loop terminates when `x` is no longer greater than `reversed_half`. At this point, `x` holds the first half of the original number, and `reversed_half` holds the reversed second half.
- Even Length Numbers: If the original number had an even number of digits (e.g., `1221`), `x` and `reversed_half` will be equal (`12` and `12`).
- Odd Length Numbers: If the original number had an odd number of digits (e.g., `121`), `x` will contain the middle digit (`1`), and `reversed_half` will contain the reversed second half (`12`). In this case, `x` should be equal to `reversed_half` divided by `10` (`12 // 10` which is `1`).
Key Takeaways
- Negative numbers and numbers ending in `0` (except `0` itself) are not palindromes.
- The algorithm constructs the reversed second half of the number.
- It avoids string conversion, operating directly on integer values.
- The loop efficiently stops once half the digits have been processed.
- Final comparison handles both even and odd digit counts by checking `x == reversed_half` or `x == reversed_half // 10`.
Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.
Ask your own question →