[leetcode]: 9. Palindrome Number

来源:互联网 发布:仙剑传奇网站源码 编辑:程序博客网 时间:2024/06/05 09:02

1.题目

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

2.分析

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

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

3.代码

class Solution {public:    bool isPalindrome(int x) {        if (x < 0 || (x != 0 && x % 10 == 0))            return false;        int right = 0;        while (x > right) {            right = right * 10 + x % 10;            x /= 10;        }        return x == right || right / 10 == x;//奇数位    }};