【Palindrome Number】cpp
题目:
Determine whether an integer is a palindrome. Do this without extra space.
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.
代码:
class Solution { public: bool isPalindrome(int x) { if (x<0) return false; return x==Solution::reverse(x); } static int reverse(int x) { int ret = 0; while (x) { if ( ret>INT_MAX/10 || ret<INT_MIN/10 ) return 0; ret = ret*10 + x%10; x = x/10; } return ret; } };
tips:
1. 如果是负数,认为不是回文数
2. 如果是非负数,则求这个数的reverse,如果等于其本身就是回文数,否则就不是。
利用的就是reverse integer这道题(http://www.cnblogs.com/xbf9xbf/p/4554684.html)。
====================================
还有一种解法可以不用reverse,有点儿类似求字符串是否是回文的题目(头尾两个指针往中间夹逼)。
class Solution { public: bool isPalindrome(int x) { if (x<0) return false; int d = 1; while ( x/d>=10 ) d = d*10; while ( x>0 ) { int high = x/d; int low = x%10; if (high!=low) return false; x = x%d/10; d = d/100; } return true; } };
对于这道题的整数来说,就是找到给定整数的最大位数-1,即d。
每次从高位取一个数,从低位取一个数;然后,再把高低位都去掉获得新数(x=x%d/10);这样照比上一次的数少了两位,因此还有d=d/100。
===========================================
第二次过这道题,根据题意提示,用reverse的结果判断是否是palindrome number。
class Solution { public: bool isPalindrome(int x) { if ( x<0 ) return false; int rev = Solution::reverse(x); return rev==x; } static int reverse(int x) { vector<int> digits; int sign = x>0 ? 1 : -1; int ret = 0; while ( true ) { int digit = fabs(x%10); if ( INT_MAX/10<ret || (INT_MAX/10==ret && INT_MAX%10<digit) ) { return 0; } ret = ret*10 + digit; x = x/10; if ( fabs(x)==0 ) break; } return ret*sign; } };