題目: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;
}
};