LeetCode 476 Number Complement (Python)

Posted by 小明MaxMing on May 4, 2020

题目

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

解题思路

对应一个n位数m,最后的结果为(2**n - 1) ^ m (2的n次幂减一的结果异或m)

代码

class Solution:
    def findComplement(self, num: int) -> int:
        x = 1
        while x <= num:
            x <<= 1
        return (x - 1) ^ num

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅