LeetCode 9: Palindrome Number Solution
Master LeetCode problem 9 (Palindrome Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
9. Palindrome Number
Problem Explanation
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)
:
Solution Code
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;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 9 (Palindrome Number)?
This page provides optimized solutions for LeetCode problem 9 (Palindrome Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 9 (Palindrome Number)?
The time complexity for LeetCode 9 (Palindrome Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 9 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 9 in Java, C++, or Python.