add complement of base 10 integer soln
This commit is contained in:
18
1054_complement-of-base-10-integer/python3/linear.py
Normal file
18
1054_complement-of-base-10-integer/python3/linear.py
Normal 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
|
||||
17
1054_complement-of-base-10-integer/python3/solution.py
Normal file
17
1054_complement-of-base-10-integer/python3/solution.py
Normal 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
|
||||
Reference in New Issue
Block a user