题目:Determine whether an integer is a palindrome. Do this without extra space.
解法1、需要额外空间:
存储各位数字,逆转,换回逆转值,与原值比较
class Solution {
public:
int reverse(int x) {
long long sum=0;
long long result=0;
bool negative=false;
vector<int> temp;
if(x<0){
negative=true;
sum=-x;
}else{
sum=x;
}
while(sum>=10){
temp.push_back(sum%10);
sum=sum/10;
}
temp.push_back(sum);
bool isnotZore=false;
for(int i=0;i<temp.size();i++){
if(temp[i]!=0){
isnotZore=true;
}
if(isnotZore){
if(negative){
result*=10;
result-=temp[i];
}else{
result*=10;
result+=temp[i];
}
}
}
if(result>~(1<<31)){
return 0;
}else if(result<(1<<31)){
return 0;
}else {
return result;
}
}
bool isPalindrome(int x) {
if(x<0) return false;
return x==reverse(x);
}
};
解法2、不需额外空间
每次,取出数的最高位和最低位比较,这里设置一个base为10^n,用来取出数的最高位,每次循环除以100,因为每次数会消去2位。
class Solution {
public:
bool isPalindrome(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (x < 0)
return false;
if (x == 0)
return true;
int base = 1;
while(x / base >= 10)
base *= 10;
while(x)
{
int leftDigit = x / base;
int rightDigit = x % 10;
if (leftDigit != rightDigit)
return false;
x -= base * leftDigit;
base /= 100;
x /= 10;
}
return true;
}
};