LeetCode #9 简单题 (判断数字回文)

题目:判断一个整数是不是回文

题解:对于负数或者以0结尾而且不是0的数,肯定是false,对于其他数,用另外一个数y存一下反正后的数字,然后开始给x反转存到y中,当y >= x的时候,反转停下,毕竟x和y和y,如果x和y相等(偶数个数字)或者y/10等于x(奇数个数字),那么就是回文了

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

猜你喜欢

转载自www.cnblogs.com/error408/p/11610611.html