9. Palindrome Number

Math

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)

:

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.