本文共 1588 字,大约阅读时间需要 5 分钟。
题目描述
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:先算出数字的位数,然后循环比较对应位数字是否相同,若相同,则继续比较;若不同,则返回false。
思路2:反转数字(注意溢出问题)
代码:
#include#include using namespace std;bool isPalindrome(int x);bool isPalindrome_2(int x);int main(){ cout << isPalindrome(100801) << endl; return 0;}bool isPalindrome(int x){ if(x < 0) return false; int count = 1; int a = x; while(a/10 != 0){//计算数字位数 ++count; a = a/10; } int tenH = pow(10, count - 1);//初始化tenH,用来计算高位数字 int tenL = int(pow(10, 1));//初始化tenL,用来计算低位数字 int i; for(i = 1; i <= count/2; ++i){ //int h = x / pow(10, count - i); int h = x / tenH; tenH = tenH / 10;//更新tenH if(h >= 10) h = h % 10; //int l = x % int(pow(10, i)); //l = l / int(pow(10, i-1)); int l = x % tenL; l = l / (tenL / 10); tenL = tenL * 10;//更新tenL //cout << "h: " << h << " l: " << l << endl;//测试输出 if(h != l)//比较对应位 return false; } return true;}bool isPalindrome_2(int x) { int res=0; int tmp=x; if(x<0) return false; while(tmp) { res=res*10+tmp%10;//此公式可自动处理末尾为0而逆反带来的溢出问题 tmp/=10; } if(res==x) return true; else return false;}
转载地址:http://ixnii.baihongyu.com/