Skip to content

Commit aefc800

Browse files
committed
number complement in bitmasking added
1 parent 8e79806 commit aefc800

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Bitmasking/number_complement.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'''
2+
https://leetcode.com/problems/number-complement/
3+
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
4+
5+
Example 1:
6+
Input: 5
7+
Output: 2
8+
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
9+
'''
10+
11+
class Solution:
12+
def countBits(self, num: int):
13+
count = -1
14+
while(num):
15+
num = num >> 1
16+
count += 1
17+
return count
18+
19+
# method - 1
20+
def findComplement(self, num: int):
21+
22+
c = self.countBits(num)
23+
mask = 0
24+
while(c>=0):
25+
mask = mask | (1<<c)
26+
c -= 1
27+
28+
num = num ^ mask
29+
30+
return num
31+
32+
# method - 2
33+
def findComplement(self, num: int):
34+
35+
bit_count = self.countBits(num)
36+
37+
# num = 5 = 101
38+
# c = 3
39+
# 2^3 = 8 = 1000
40+
# mask = 8-1 = 7 = 111
41+
# num^mask = 101^111
42+
43+
mask = (1 << (bit_count)) - 1
44+
return num^mask

0 commit comments

Comments
 (0)