Determine whether an integer is a palindrome. Do this without extra
space.
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.
题解:
求解回文数(提示,回文数是指一个数A,将其翻转之后的到数B,且有A=B, 例如: 1,11 , 131, 65356 等)
(1) 回文数是自然数,最小的回文数为0
(2) 不能使用额外存储空间, 因此不能采用字符串翻转来做。
(3) 不能直接将整个数翻转过来,可能出现“溢出”。
受到条件(3)的启发, 既然不能整个翻转,能否部分翻转呢? 尝试之后发现有如下结论:
将数A分成左右相等的部分(高位部分A1,低位部分A2):
特别的:
如果A的长度为奇数,那么处于中间数位的数字对于回文比较不会产生影响。因此可以忽略。
将A2 翻转,得到A2‘ ,那么有
若A1 = A2’ , A为回文数
否则A不是回文数。