Crack LeetCode 之 9. Palindrome Number

这一题巧妙运用取余和除法运算来取十进制数字的高位和低位。之前我还想到过把数字转为字符串,然后再检查,但是这样效率比较低。以下为C++的代码和python的代码,时间复杂度是O(n),空间复杂度是O(1)。

struct Solution {
    bool isPalindrome(int x) {
        if (x < 0)
            return false;

        int div = 1;
        while (div <= x / 10)
            div *= 10;

        while (x > 0) {
            if (x / div != x % 10)
                return false;

            x = (x%div) / 10;
            div /= 100;
        }

        return true;
    }
};
class Solution:
    def isPalindrome(self, x):
        if x < 0:
            return False

        div = 1
        while div <= int(x/10):
            div = div * 10

        while x>0 :
            if (x%10) != int(x/div):
                return False
            
            x = int((x%div)/10)
            div = int(div / 100)

        return True


 

猜你喜欢

转载自blog.csdn.net/tassardge/article/details/84839194