Determine whether an integer is a palindrome. Do this without extra space. Assume that a negative integer is not a palindrome.
public boolean isPalindrome(int x) {
if (x < 0) // Negative numbers are assumed to be non-palindromic
return false;
// The smallest integer that has the same number of digits with x
// Used to get the leftmost digit
int oneZeros = 1;
while (x / oneZeros >= 10)
oneZeros *= 10;
// Compare the digits at both ends
while (x != 0) {
int leftmost = x / oneZeros;
int rightmost = x % 10;
if (leftmost != rightmost)
return false;
x = (x % oneZeros) / 10; // Chop the leftmost and rightmost digits
oneZeros /= 100; // Update oneZeros as two digits are chopped
}
return true;
}
Read full article from LeetCode - Palindrome Number | Darren's Blog
No comments:
Post a Comment