Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.
解法1: Reverse integer O(N), N is the number of digits
用一个循环来反转数字,最后比较数字和反转的是否相等即可。
C++
Java
解法2: Without overflow
比较最左边和最右边的两个数,这样就不会有overflow的问题了。 取得左边的数的时候我们需要的是一个除数,这个可以先用O(N)的时间求出。
然后每次求出最右位和最左位。然后每次消掉两位数,相应的div也要缩小100
C++