-
Notifications
You must be signed in to change notification settings - Fork 0
9. Palindrome Number
Jacky Zhang edited this page Oct 31, 2016
·
4 revisions
Determine whether an integer is a palindrome. Do this without extra space.
这个题目的注意点:
- 负数认为不是回文,返回false;
- 若用reverse integer来比较,则需考虑溢出问题;
- 考虑xx0的情况,如220等,翻转后20会变成2,会错判为true,需要避免。
因此可以只翻转一半数字,与另一半比较,这样就避免了溢出的问题。
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0 || (x != 0 && x%10 == 0)) {
// x is negative, x is like 'xx0', 0 is true
return false;
}
int rev = 0;
while(x > rev) {
rev = rev * 10 + x % 10;
x = x / 10;
}
// x is like 'abba' or 'aba'
return (x == rev || x == rev/10);
}
}