[LeetCode] #9 Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

看到题目第一想法是将数字倒过来相减,看是否为0,但是会超时。原因是大部分可能并不是,所以循环中间就退出循环了。目前这个程序是按最左位与最右位逐次比较。时间:29ms

代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0)
            return false;
        if (x == 0)
            return true;
            
        int base = 1;
        while(x / base >= 10)
            base *= 10;
            
        while(x)
        {
            int leftDigit = x / base;
            int rightDigit = x % 10;
            if (leftDigit != rightDigit)
                return false;
            
            x -= base * leftDigit;
            base /= 100;
            x /= 10;
        }
        
        return true;
    }
};
“If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
原文地址:https://www.cnblogs.com/Scorpio989/p/4418293.html