Palindrome Number
9.Palindrome Number
Math
Two Pointers
Problem Statement:
Given an integer x, return true if x is a palindrome, and false otherwise. An integer is a palindrome when it reads the same forward and backward.
Example:
Input:
x = 121→
Output:
true121 reads as 121 from left to right and right to left.
Algorithm:
- Check if number is negative (not palindrome)
- Store original number for comparison
- Build reverse of number by extracting digits
- Compare original with reversed number
Complexity:
Time: O(log n) | Space: O(1)
Java Solution:
public boolean isPalindrome(int x) {
int num = x;
int n = 0;
// Negative numbers are not palindromes
if (x < 0) return false;
while (x != 0) {
// Build reversed number digit by digit
int last = x % 10;
n = n * 10 + last;
x /= 10;
}
return n == num;
}
Python Solution:
def isPalindrome(self, x: int) -> bool:
# Negative numbers are not palindromes
if x < 0:
return False
num, n = x, 0
while x:
# Build reversed number digit by digit
n = n * 10 + x % 10
x //= 10
return n == num
C++ Solution:
bool isPalindrome(int x) {
// Negative numbers are not palindromes
if (x < 0) return false;
long num = x;
long n = 0;
while (x != 0) {
// Build reversed number digit by digit
n = n * 10 + x % 10;
x /= 10;
}
return n == num;
}