Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
Be careful with potential overflow !
public boolean isPalindrome(int x) { if(x < 0) return false; int base = 1; while((x / 10) / base > 0) // remember here might overflow! base = base * 10; while(base > 1) { int a = x / base; int b = x % 10; if(a != b) return false; x = x % base; x = x / 10; base = base / 100; } return true; }
没有评论:
发表评论