题目
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.
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.
思路
首先要注意,负数不是回文数。
然后题目中要求不能使用额外的空间,我的理解是O(1)空间复杂度,即不能用字符串来存储?
代码
我这个解决方案不知道是不是违规了,如果再苛刻一点,那就是每次测试当前数字的位数(连续除10),然后用除法和模10判断首位和末尾的数字。
class Solution { public: bool isPalindrome(int x) { if(x < 0) return false; int cover = 1; int x_copy = x; while(x_copy/10 > 0){ x_copy /= 10; cover *= 10; } while(cover >= 10){ int front = x/cover; int end = x%10; if(front != end){ return false; } x -= front * cover; x /= 10; cover /= 100; } return true; } };