问题描述:
Determine whether an integer is a palindrome. Do this without extra space.
思路:这个问题需要注意的第一个问题是不能使用额外的空间,也就是说我们可以在反转字符串一半的时候进行判断。接下来要注意的问题有那么几个,一个是负数不是回文数,个位数也不是回文数,然后我们用一个whille循环不断反转就可以了,一旦反转超过一半就停止。最后需要注意的问题就是回文可能是奇数位或者偶数位,所以返回反转和原来的相等或者反转的比原来的大都是正确的。
代码:
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
bool isPalindrome(int x){
if(x < 0 || (x != 0 && x / 10 == 0)) return false;
int sum = 0;
while(x > sum){
sum = sum * 10 + x % 10;
x /= 10;
}
return (x == sum || x == sum / 10);
}
int main(){
int a = 12321;
int b = 123321;
cout<<"input a:";
cin>>a;
cout<<"a:"<<a<<endl<<"is palindrome ?"<<isPalindrome(a)<<endl;
}
复杂度: O(1)