题目信息
解题思路
法1:转化成字符串
将数转化成字符串再用字符串的方法判断回文。
法2:翻转一半
取出前半段(后半段)数(代码中是后半段)进行翻转,判断是否与原数相等。
代码实现
法1
class Solution {
public:
// 将数转化为字符串
string to_string(int x) {
string res;
while (x) {
res += x % 10 + '0';
x /= 10;
}
return res;
}
// 判断一个字符串是否为回文串
bool judge(string s) {
int n = s.size();
for (int i = 0; i < n / 2; ++i) {
if (s[i] != s[n - i - 1]) {
return false;
}
}
return true;
}
bool isPalindrome(int x) {
if (x < 0) { // 负数不是回文数
return false;
}
return judge(to_string(x));
}
};
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) { // 负数或者除0外个位是0的数(首位不可能为0)不是回文数
return false;
}
int res = 0;
while (x > res) { // x <= res的话就说明res已经至少一半了
res = res * 10 + x % 10;
x /= 10;
}
return x == res || x == res / 10; // 如果x是奇数的话,中间数就会在最后
}
};