[leetcode]: 9. Palindrome Number
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;//奇数位
}
};
还没有评论,来说两句吧...