19 lines
418 B
Python
19 lines
418 B
Python
|
# 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
|