您的位置:首页 > 其它

leetcode——Palindrome Number 判断整数数字是否为回文(AC)

2014-06-08 09:38 344 查看
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.
这道题加了不能使用额外空间的限制,如果没有这个限制的话,我们大可以开辟一个字符串数组把整数的各位数字存储起来,然后使用指针进行判断。在这道题目的要求之下,我们只能每次把首尾的两个数字提取出来进行比较,然后再把这两个数字从原数字钟剔除,继续比较。。。直到所有数字比完,就可得出是回文的结论。个位数提取只需对10取余即可,最高位提取需要将原数字除以10^n次方即可。还有需要注意的是题目要求负数不存在回文。code如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int base = 1;
int temp = x;
while((temp=temp/10) != 0)
base *= 10;
temp = x;
while(temp != 0)
{
if(temp%10 == temp/base)
{
temp = (temp - temp/base*base)/10;
base /= 100;
}
else
{
return false;
}
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  回文 整数