Determine whether an integer is a palindrome. Do this without extra space.
判断一个整数是不是“回文”。
思路:将整数反转,然后判断两者是否相等。
附上代码:
#include <iostream>
#include <climits>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) // add
return false;
if(x==reverse(x))
return true;
else
return false;
}
int reverse(int x)
{
int result = 0;
if(result>INT_MAX/10 || result<INT_MIN/10)
return 0;
while(x!=0)
{
result = result*10+x%10;
x/=10;
}
return result;
}
};
int main()
{
int x;
cin>>x;
Solution s;
cout<<s.isPalindrome(x);
return 0;
}
错误原因是:负数都不算是“回文”。所以做题要考虑周全,面试的话要沟通全面!