题目
9-回文数
https://leetcode-cn.com/problems/palindrome-number/

题解
核心考点:
- 想到用翻转数字的方法来判断回文数字;
- 对于特殊的以0结尾的非0数,以及所有负数的情况,提前返回;
- 什么时候停止判断的,这个非常巧妙!任务如果翻转超过一半时得到的数字大于或者等于原来的数字时,则停止。
- 但是,如果反转后的数字大于 \text{int.MAX}int.MAX,我们将遇到整数溢出问题 => 为了避免数字反转可能导致的溢出问题,为什么不考虑只反转 int 数字的一半?毕竟,如果该数字是回文,其后半部分反转后应该与原始数字的前半部分相同。(int 32位)
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/palindrome-number/solution/hui-wen-shu-by-leetcode-solution/
来源:力扣(LeetCode)
附代码:
class Solution {
public:
bool isPalindrome(int x) {
// 考虑0的情况,在mod时记得加上判断
if (x < 0 || (x > 0 && x % 10 == 0)) {
return false;
}
int reversed = 0;
while (x > reversed) {
reversed = reversed * 10 + x % 10;
x = x / 10;
}
// 多乘的除回来即可
if (x == reversed || x == reversed / 10) {
return true;
}
return false;
}
};
博客围绕LeetCode的回文数题目展开,介绍题解核心考点。包括用翻转数字判断回文,提前处理以0结尾非0数和负数情况,还提到为避免溢出只反转数字一半,当翻转超过一半时停止判断,最后附上代码。
2935

被折叠的 条评论
为什么被折叠?



