Palindrome Number | LeetCode in C#
How I solved palindrome number checker without string conversion
Problem
Given an integer x
, return true
if x
is a palindrome , and false
otherwise.
Example 1:
- Input:
x = 121
- Output:
true
- Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
- Input:
x = -121
- Output:
false
- Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
- Input:
x = 10
- Output:
false
- Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
Intuition
A number is a palindrome if it reads the same forwards and backwards. The first thought might be to convert the number into a string and check if it matches its reverse. However, the challenge is to solve this without converting the integer to a string, which calls for a numerical approach.
Approach
To determine if an integer is a palindrome without using string conversion, we reverse the integer by repeatedly extracting its last digit and appending it to a new reversed number. Here’s how:
- Negative Numbers: Start by handling negative numbers. Any negative number cannot be a palindrome since the negative sign only appears on one side.
- Reverse Integer: Initialize
reverseNumber
to zero and a copy of the inputx
calledy
. Whiley
is greater than zero, repeatedly:- Extract the last digit (
y % 10
) fromy
and append it toreverseNumber
by multiplyingreverseNumber
by 10 and adding the digit. - Remove the last digit from
y
by performing integer division by 10.
- Extract the last digit (
- Comparison: After constructing the reversed integer, compare it to the original number
x
. If they are identical,x
is a palindrome.
This approach effectively reconstructs the reversed number without needing the original number’s length or auxiliary string manipulations.
Complexity
-
Time complexity: The time complexity is \(O(\log_{10}(n))\) because we iterate through all the digits of the number
x
, wheren
is the input value. -
Space complexity: The space complexity is \(O(1)\) as we only use a few extra variables to store numbers, regardless of the input size.
Code
Video
Conclusion
By reversing the integer numerically, this algorithm cleverly checks for palindromes without converting the number to a string, thus adhering to the problem’s constraints while maintaining an efficient space complexity. This method ensures that we can handle large integers within the problem’s constraints effectively.
This discussion provides a clear understanding of how to determine if a number is a palindrome via integer arithmetic, avoiding the pitfalls of converting to a string.