leetcode/1054_complement-of-base-10-integer/python3/solution.py

18 lines
496 B
Python
Raw Permalink Normal View History

2022-04-12 19:08:54 +00:00
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1
mask = n
# Create mask of length matching num of bits
# in n (taken from Hacker's Delight, Figure 3-1)
mask |= mask >> 1 # \
mask |= mask >> 2 # \
mask |= mask >> 4 # |> Totalling 31 bits
mask |= mask >> 8 # /
mask |= mask >> 16 # /
# XOR 1 will flip the bit
return n ^ mask