[Leetcode problem solution] 476. Number's complement (bitwise exclusive OR)

Leetcode question solution
link: 476. Number's complement
solution idea: Complement is required. Since the exclusive OR of any number to 1 is the inverse of itself, it can be solved by the exclusive OR property.
answer:

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

Guess you like

Origin blog.csdn.net/qq_37753409/article/details/109271704