add complement of base 10 integer soln

This commit is contained in:
2022-04-13 00:38:54 +05:30
parent 5820974811
commit 658601137a
6 changed files with 127 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
# 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

View File

@@ -0,0 +1,17 @@
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