[leetcode]: 9. Palindrome Number

╰半橙微兮° 2022-06-15 09:45 248阅读 0赞

1.题目

Determine whether an integer is a palindrome. Do this without extra space.
判断一个数是否回文数,不适用额外空间

2.分析

回文数例如 1,101,1221,是对称的。
1)负数不是回文
2)回文数末尾不是0

所以可以将数分为两部分xxxyyy,判断两部分是否相等。

3.代码

  1. class Solution {
  2. public:
  3. bool isPalindrome(int x) {
  4. if (x < 0 || (x != 0 && x % 10 == 0))
  5. return false;
  6. int right = 0;
  7. while (x > right) {
  8. right = right * 10 + x % 10;
  9. x /= 10;
  10. }
  11. return x == right || right / 10 == x;//奇数位
  12. }
  13. };

发表评论

表情:
评论列表 (有 0 条评论,248人围观)

还没有评论,来说两句吧...

相关阅读