LeetCode #9 Palindrome Number (E)
[Problem]
Determine whether an integer is a palindrome. Do this without extra space.
[Analysis]
这题不能转换为String来做因为要求constant space。只要依次比较头尾两个数字就可以了。
[Solution]
public class Solution { public boolean isPalindrome(int x) { if (x < 0) { return false; } // initialize base int base = 1; while (x/base >= 10) { base *= 10; } while (x != 0) { int leftMost = x/base; int rightMost = x % 10; if (leftMost != rightMost) { return false; } else { x = (x % base) / 10; base /= 100; } } return true; } }