#include<iostream>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
{
return false;
}
char str[20];
sprintf(str, "%d", x);
int len = strlen(str);
for (int i = 0; i < len / 2; i++)
{
char temp=str[i];
str[i] = str[len - 1 - i];
str[len - i - 1] = temp;
}
int y;
sscanf(str, "%d", &y);
if (x==y)
{
return true;
}
return false;
}
};
int main()
{
Solution p;
cout<<p.isPalindrome(-2)<<endl;
system("pause");
return 0;
}
2、方法二:将数字本身反转,然后将反转后的数字与原始数字进行比较
#include<iostream>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || x % 10 == 0 && x != 0)
{
return false;
}
int y = 0;
while (x > y)
{
y = y * 10 + x % 10;
x = x / 10;
}
if (x == y || x == y / 10)
{
return true;
}
return false;
}
};
int main()
{
Solution p;
cout<<p.isPalindrome(-2)<<endl;
system("pause");
return 0;
}