题目描述:
给定一个整数,求这个整数的回文数,但是有有一个要求:不能使用额外的空间,也就是想用字符串的方式处理是不可能了。不仅如此,还有其他条件,比如反转后悔溢出,负数等等。要是对回文数不熟悉,先看看百度百科
英文描述
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.
我的代码
这次我的代码不怎么好,效率一般,运行时间是129ms1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27bool Solution009::isPalindrome(int x)
{
if(x < 0)
return false;
int high = 1;
int low = 10,clow = 1;
int t =x;
while(t/10)
{
t /=10;
high *= 10;
}
while(high/10)
{
int h = (x / high)%10;
int l = (x % low)/clow;
if( h==l)
{
clow *= 10;
low *= 10;
high /= 10;
}
else
return false;
}
return true;
}
解题思路
我的解题思路很简单,就是设置两个指针,分别从前往后和从后往前遍历,但是这里不是字符串,指针就不合适了,我就是从高位向地位取数,和从地位向高位取数,然后做比较。
这里看似比较简单,其实在取高位数的时候容易产生溢出,所以一定要小心。