题目

Determine whether an integer is a palindrome. Do this without extra space.

大意

不使用额外空间判断一个数是否是回文数

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool isPalindrome(int x) {
int res = 0, k = x;
if(x<0) x=-x;
while(x!=0)
{
res = res*10 + x%10;
x = x/10;
}
if(k==res)
{
return true;
}
else
{
return false;
}
}
};

思路

可以直接算出反过来的数,然后与原数对比,就可以判断了.

这里主要说明直接算相反数的方法 ,x是原数,res 是最后算出来的相反数.

1
2
3
4
5
while(x!=0)
{
res = res*10 + x%10;
x = x/10;
}