Skip to content

Commit ebb57d6

Browse files
committed
a binary format problem
1 parent 60582ef commit ebb57d6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# not dp, but using binary as the question is all about binary operations.
2+
class Solution:
3+
def minOperations(self, n):
4+
if n == 0:
5+
return 0
6+
if n == 1:
7+
return 0
8+
if n < 0:
9+
return 0
10+
11+
# do comparison with either makes up with 1 or not
12+
ret = 0
13+
# pos int n means it is single precision
14+
for i in range(32):
15+
if self.count_1(n + (1 << i)) + 1 <= self.count_1(n): # in fact, it considers the case of subtraction, coz if it is 0b'10000000001, apparently it won't get into the loop, and the result will just ret + self.count_1(n), which is done by doing substation
16+
n += 1 << i
17+
ret += 1
18+
return ret + self.count_1(n)
19+
20+
def count_1(self, n):
21+
binary_n = bin(n)
22+
return binary_n.count('1')
23+
24+
25+
# indata = [3, 2, 0, -4]
26+
# pos = 1
27+
# indata = 39
28+
# output = 3
29+
indata = 54
30+
output = 3
31+
sol = Solution()
32+
out = sol.minOperations(indata)
33+
print(out)

0 commit comments

Comments
 (0)