【LeetCode 题解】系列传送门: http://www.cnblogs.com/double-win/category/573499.htmlhtml
Determine whether an integer is a palindrome. Do this without extra space.git
Some hints:this
Could negative integers be palindromes? (ie, -1)spa
If you are thinking of converting the integer to string, note the restriction of using extra space.rest
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?code
There is a more generic way of solving this problem.htm
判断一个整数是不是回文数。要求使用常量空间。blog
提示:ci
(1)负数是不是回文数?字符串
(2)注意常量空间复杂度。将数字转换成字符串是不可行的。
若是将整个数字转换再判断是不是回文数,那么就可能出现反转以后的数字越界。
延续这个思路,可否经过某些技巧来避免越界呢?先看下面的例子:
(1) 1234321 / 12344321
将数字分红等长的两部分: 1234 和 4321。那么能够看出 4321 反转以后的数字为1234. 二者相等,因此1234321为回文数。
(2) 12345321
将数字分红等长的两部分: 1234 和 5321。那么能够看出 5321 反转以后的数字为1235.
因为1234!=1235,因此12345321不是回文数。
从上面两个例子能够看出。在处理一个数字是不是回文数的过程当中,没有必要将整个数字反转。而只须要判断数字的先后等长的两部分时候相等便可。
那么如何在常量空间复杂度内,将数字分红先后两部分呢?
记 须要判断的数字为x,其前一部分为firstpart=x,后一部分为secondpart=0.
采起依次取firstpart的末位,将其添加到secondpart的尾部的方式,直到firstpart<=secondpart.
firstpart | secondpart |
1234321 | 0 |
123432 | 1 |
12343 | 12 |
1234 | 123 |
123 | 1234 |
当firstpart<secondpart时,只需反过来将secondpart最后一位转移到firstpart末位便可。
tmp=1234%10=4;
firstpart=firstpart*10+tmp=123*10+4=1234。
此时secondpart也为1234.
所以1234321为回文数。
class Solution { public: bool isPalindrome(int x) { int first=x,second=0,tmp; if(x==0) return true; //zero if(x<0|| x%10==0) return false; //negative number or the number is dividable by 10 while(first>second){ // reverse the number tmp=first%10; second= second*10+tmp; first/=10; } if(first==second) return true; else{ // handle the number with odd digits tmp = second%10; first=first*10+tmp; if(first==second) return true; else return false; } return false; } };