You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an integer x, return trueifxis a _ palindrome_ , andfalseotherwise.
Example 1:
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
Example 2:
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) div *= 10;
while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
};
请点击下方图片观看讲解视频
Click below image to watch YouTube Video
Given an integer
x
, returntrue
ifx
is a _ palindrome_ , andfalse
otherwise.Example 1:
Example 2:
Example 3:
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
这道验证回文数字的题如果将数字转为字符串,就变成了验证回文字符串的题,没啥难度了,我们就直接来做 follow up 吧,不能转为字符串,而是直接对整数进行操作,可以利用取整和取余来获得想要的数字,比如 1221 这个数字,如果 计算 1221 / 1000, 则可得首位1, 如果 1221 % 10, 则可得到末尾1,进行比较,然后把中间的 22 取出继续比较。代码如下:
解法一:
再来看一种很巧妙的解法,还是首先判断x是否为负数,这里可以用一个小 trick,因为整数的最高位不能是0,所以回文数的最低位也不能为0,数字0除外,所以如果发现某个正数的末尾是0了,也直接返回 false 即可。好,下面来看具体解法,要验证回文数,那么就需要看前后半段是否对称,如果把后半段翻转一下,就看和前半段是否相等就行了。所以做法就是取出后半段数字,进行翻转,具体做法是,每次通过对 10 取余,取出最低位的数字,然后加到取出数的末尾,就是将 revertNum 乘以 10,再加上这个余数,这样翻转也就同时完成了,每取一个最低位数字,x都要自除以 10。这样当 revertNum 大于等于x的时候循环停止。由于回文数的位数可奇可偶,如果是偶数的话,那么 revertNum 就应该和x相等了;如果是奇数的话,那么最中间的数字就在 revertNum 的最低位上了,除以 10 以后应该和x是相等的,参见代码如下:
解法二:
下面这种解法由热心网友 zeeng 提供,如果是 palindrome,反转后仍是原数字,就不可能溢出,只要溢出一定不是 palindrome 返回 false 就行。可以参考 Reverse Integer 这题,直接调用 Reverse()。
解法三:
Github 同步地址:
#9
类似题目:
Palindrome Linked List
Reverse Integer
参考资料:
https://leetcode.com/problems/palindrome-number/
https://leetcode.com/problems/palindrome-number/discuss/5127/9-line-accepted-Java-code-without-the-need-of-handling-overflow
LeetCode All in One 题目讲解汇总(持续更新中...)
(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)
喜欢请点赞,疼爱请打赏❤️~.~
微信打赏
|
Venmo 打赏
---|---
The text was updated successfully, but these errors were encountered: