【Leetcode题解】476. 数字的补数 (位运算 异或)

Leetcode 题解
题目链接: 476. 数字的补数
解题思路: 要求补数,由于任何数对于1的异或为本身取反,所以可以用异或性质求解。
题解:

import math
class Solution:
    def findComplement(self, num: int) -> int:
        if num == 0: return 1
        return num ^ ((1 << int(math.log2(num)) + 1) - 1)

猜你喜欢

转载自blog.csdn.net/qq_37753409/article/details/109271704