Determine whether an integer is a palindrome. Do this without extra space.
解法一:
最naive的解法就是不考虑space的开销。先转成digits,再进一步比较vector。
class Solution {
public:
bool isPalindrome(int x) {
if (x<0) return false;
vector<int> digits;
while(x){
digits.push_back(x%10);
x = floor(x/10);
}
int size = digits.size();
for(int i= 0; i< size/2; i++){
if (digits[i]!= digits[size-i-1])
return false;
}
return true;
}
};
解法二:
这里使用 pow和log10去获取当前数字最高位对应的整数。需要注意是每一次,base = base/100。之前犯得错误是在while中更新base是不对的。
class Solution {
public:
bool isPalindrome(int x) {
if (x<0) return false;
int base = pow(10,floor(log10(x)));
while (x>0){
int i = floor(x/base);
int j = (x%10);
if (i!=j) return false;
x = (x%base)/10;
base /= 100;
}
return true;
}
};