Determine whether an integer is a palindrome. Do this without extra space.
判断一个整数是否为回文,解决思路很简单,就是不断取整数的第一位和最后一位进行比较,相等则继续取第二位和倒数第二位,直到整数的所有位都比较完成或者中途找到了不一致的位。
#include<iostream>
#include<algorithm>
using namespace std;
class solution{
public:
bool isPalindrome(int x){
if (x < 0) return false;
int d = 1;
while (x / d >= 10) d *= 10;
while (x > 0){
int q = x / d;
int r = x % 10;
if (q != r) return false;
x = x%d / 10;//x%d结果为整数x除去第一位后剩下的部分,x%d / 10为x除去第一位和倒数第一位后剩下的中间部分
d = d / 100;
}
return true;
}
};
int main()
{
int x1 = 23432;
solution sol;
bool t = sol.isPalindrome(x1);
cout << t << endl;
system("pause");
return 0;
}