-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1009_complement_of_base_10_integer.py
More file actions
45 lines (30 loc) · 1000 Bytes
/
Copy path1009_complement_of_base_10_integer.py
File metadata and controls
45 lines (30 loc) · 1000 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution2:
def bitwiseComplement(self, n: int) -> int:
binary = list(self.convert_to_binary(n))
for i in range(len(binary)):
if binary[i] == '0':
binary[i] = '1'
else:
binary[i] = '0'
return self.convert_to_dec("".join(binary))
def convert_to_binary(self, n) -> str:
if n <= 0: return "0"
res = ""
while n != 0:
r = n % 2
res = str(r) + res
n = n // 2
return res
def convert_to_dec(self, binary):
length = len(binary)
res = 0
for i in range(length):
index = length - i - 1
res += int(binary[index]) * pow(2, i)
return res
class Solution:
def bitwiseComplement(self, n: int) -> int:
mask = 1
while mask < n:
mask = (mask << 1) + 1
return mask ^ n