Number Complement

就是利用满位1和当前数异或结果就是需要的值,只是这里需要计算出输入数到底有多少个bit位

class Solution(object):
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        count = 0
        tmp = num
        while tmp:
            tmp = tmp >> 1
            count += 1
        return (2 ** count - 1) ^ num

results matching ""

    No results matching ""