这一题也很简单,用了80ms,ac代码如下。思路就是:把各个位数据的ASCII码存在string中,然后用迭代器和反向迭代器查找对比,迭代一半的长度即可。
bool isPalindrome(int x) {
if (x < 0)
return false;
if(x == 0) return true;
string result;
int val = x;
while (val != 0)
{
result.push_back(val % 10);//result.push_back(val % 10 + '0');如果这样的话要多耗4ms....
val /= 10;
}
string::iterator ite = result.begin();
string::reverse_iterator rite = result.rbegin();
string::iterator half = result.begin() + result.size() / 2;
while (ite <= half && *ite == *rite)
{
++ite;
++rite;
}
return ite > half;
}
另一种是直接转化的方法
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
return false;
if(x == 0) return true;
double result = 0;
int temp = x;
while(temp != 0)
{
result = result*10 + temp%10;
temp /= 10;
}
return result == x;
}
};