We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b419312 commit e9dde76Copy full SHA for e9dde76
397.Integer-Replacement.py
@@ -0,0 +1,26 @@
1
+# https://leetcode.com/problems/integer-replacement/description/
2
+#
3
+# algorithms
4
+# Medium (30.67%)
5
+# Total Accepted: 34.5k
6
+# Total Submissions: 112.5k
7
+# beats 100.0% of python submissions
8
+
9
10
+class Solution(object):
11
+ def integerReplacement(self, n):
12
+ """
13
+ :type n: int
14
+ :rtype: int
15
16
+ res = 0
17
+ while n != 1:
18
+ if bin(n)[-1] == '0':
19
+ n = n >> 1
20
+ else:
21
+ if bin(n)[-2] == '1' and len(bin(n)) != 4:
22
+ n += 1 # if '11' +1
23
24
+ n -= 1 # if '01' -1
25
+ res += 1
26
+ return res
0 commit comments