Palindrome Number Explained
Problem Statement
Given an integer x
, determine if it is a palindrome. An integer is a palindrome when it reads the same forwards and backwards. For example, 121 is a palindrome, but 123 is not. This problem tests your ability to manipulate numbers without converting them to strings for an efficient solution.
Example
Input: x = 121
Output: true
Explanation: 121 reads the same forwards and backwards.
Code
Java
Python
JavaScript
public class Solution { public boolean isPalindrome(int x) { if (x < 0) return false; int reversed = 0, original = x; while (x > 0) { int digit = x % 10; if (reversed > Integer.MAX_VALUE / 10) return false; reversed = reversed * 10 + digit; x /= 10; } return reversed == original; } public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.isPalindrome(121)); // true } }
def is_palindrome(x): if x < 0: return False reversed_num = 0 original = x while x > 0: digit = x % 10 reversed_num = reversed_num * 10 + digit x //= 10 return reversed_num == original # Example usage print(is_palindrome(121)) # True
function isPalindrome(x) { if (x < 0) return false; let reversed = 0, original = x; while (x > 0) { let digit = x % 10; if (reversed > Math.floor(Number.MAX_SAFE_INTEGER / 10)) return false; reversed = reversed * 10 + digit; x = Math.floor(x / 10); } return reversed === original; } // Example usage console.log(isPalindrome(121)); // true
Explanation
- If the number is negative, it’s not a palindrome (e.g., -121).
- Reverse the number by extracting digits using modulo and building the reversed number.
- Check for overflow in languages like Java and JavaScript to avoid incorrect results.
- Compare the reversed number with the original.
- Return true if they match, false otherwise.
Note
This solution avoids string conversion for better efficiency, with a time complexity of O(log x) based on the number of digits. Handle edge cases like negative numbers and potential overflows carefully.