Palindrome Number
Check if an integer is a palindrome number without extra space cost (cost as we at least need
another variable). So it is not allowed to turn the number into String
with String.valueOf(x)
.
This problem is in fact quite simple but one should take care of the cases that may cause one
or more variable's value exceed their type's limit.
public class PalindromeNumber {
public static boolean isPalindrome(int x) {
if (x < 0) return false;
long l = 1; // must use long here
long r = 10;
while (x / l >= 10) l *= 10;
while (l >= r) {
long left = (x % (l * 10)) / l;
long right = (x % r) * 10 / r;
if (left != right) return false;
l /= 10;
r *= 10;
}
return true;
}
}