9. Palindrome Number
Explanation:
To determine if a given integer is a palindrome without converting it to a string, we can reverse half of the number and compare it with the other half.
- For negative numbers or numbers ending in 0 (except 0 itself), they cannot be palindromes.
- Initialize a variable
reversed
to store the reversed half of the number. - While
x
is greater thanreversed
, reverse the last digit ofx
and add it toreversed
. - If
x
has an odd number of digits, we can simply check ifx == reversed/10
. - If
x
has an even number of digits, we can check ifx == reversed
.
This approach avoids the need to convert the integer to a string.
Time complexity: O(log(x)) where x is the input number. Space complexity: O(1)
:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int reversed = 0;
while (x > reversed) {
int lastDigit = x % 10;
reversed = reversed * 10 + lastDigit;
x /= 10;
}
return x == reversed || x == reversed / 10;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.