leetcode/0476_number-complement/python3/linear.py

19 lines
415 B
Python
Raw Normal View History

2022-04-12 19:08:54 +00:00
# Time: O(N) where N is number of bits
class Solution:
def findComplement(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