目录(快速导航)
题目描述
视频讲解 https://www.bilibili.com/video/av66123241/
思路
代码
题目描述:
题目链接:https://leetcode-cn.com/problems/string-to-integer-atoi/
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
视频讲解
https://www.bilibili.com/video/av66123241/
思路:
- 所有的负数,都不是回文数;
- 整数反转,后对比反转前和反转后的整数是否一致,一致返回true,不一致返回false。
具体细节见代码。
代码:
class Solution {
public:
bool isPalindrome(int x) {
int tmp = x;
if (x < 0) {
return false;
}
else {
// 正整数反转
int out = 0;
while (x != 0) {
if (out > INT_MAX / 10 || (out == INT_MAX && (x % 10) > 7)) {
return false;
}
out = out * 10 + x % 10;
x /= 10;
}
return out == tmp;
}
}
};