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

Easy

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.

  1. For negative numbers or numbers ending in 0 (except 0 itself), they cannot be palindromes.
  2. Initialize a variable reversed to store the reversed half of the number.
  3. While x is greater than reversed, reverse the last digit of x and add it to reversed.
  4. If x has an odd number of digits, we can simply check if x == reversed/10.
  5. If x has an even number of digits, we can check if x == 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.

Back to LeetCode Solutions