leetcode/1054_complement-of-base-10-.../python3/linear.py

19 lines
418 B
Python
Raw Permalink Normal View History

2022-04-12 19:08:54 +00:00
# Time: O(N) where N is number of bits
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1
cn, bit = n, 1
while n > 0:
# XOR 1 can be used to flip bit.
# 0 XOR 1 = 1
# 1 XOR 1 = 0
cn = cn ^ bit
bit = bit << 1
n = n >> 1
return cn