LeetCode Q 9 - Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Solution
Solution 1: Transform the int to string
Code:
public boolean isPalindrome(int x) {
if (x < 0) return false;
String s = x + "";
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i++) != s.charAt(j--))
return false;
}
return true;
}
Solution 2: Revert half of the int
Second, we can revert the number itself, and then compare the number with original number, if they are the same, then the number is a palindrome. However, if the reversed number is larger than Integer.MAX_VALUE, we will hit integer overflow problem.
Following the thoughts , to avoid the overflow issue of the reverted number, what if we only revert half of the \text{int}int number? After all, the reverse of the last half of the palindrome should be the same as the first half of the number, if the number is a palindrome.
Code:
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) //30, 400,... are not palindrome
return false;
int num = 0;
while (x > num) {
num = 10 * num + x % 10;
x /= 10;
}
return x == num || x == num / 10;
}