1 题目
Determine whether an integer is a palindrome. Do this without extra space.
判断一个数字是否是回文数字,不用额外的空间。
2 分析
如果允许使用额外的空间,那么就将数字头尾颠倒,然后判断相等。但是缺陷在于,不能用在64位数字上。因为溢出以后不能判断了
可以采用掐头去尾的方式,如果头尾相等,那么就去掉头尾
class Solution
{
public:
bool isPalindrome(int x)
{
if (x < 0)
{
return false;
}
int len = 1;
// 当 x/ len 小于10的时候,len*10 就比x大了。
// 此时x%len是一个个位数
while (x / len >= 10)
{
len *= 10;
}
while (x > 0)
{
// 取头尾
int left = x / len;
int right = x % 10;
if (left != right)
{
return false;
}
else
{
// 如果想等,那么掐头去尾
x = (x % len) / 10;
len /= 100;
}
}
return true;
}
};
3 总结
嗯学到了,如何求一个数字的,嗯,就是倍数,取模以后剩下个位数。这种方式直观。