1.题目
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.我的题解
2.1 字符串解法
转为字符串,判断该字符串的反转结果是否等于该字符串。
class Solution {
public:
bool isPalindrome(int x) {
string s=to_string(x);
string s_rev=s;
reverse(s_rev.begin(),s_rev.end());
return s==s_rev;
}
};
2.2 反转数字
- 防止溢出。
- 负数可以直接判
false
;
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)return false;
long long xx=x,res=0;
while(xx){
res=res*10+xx%10;
xx/=10;
}
return res==x;
}
};