Skip to content

Commit e9dde76

Browse files
committed
feat(leetcode): add No.397
1 parent b419312 commit e9dde76

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

397.Integer-Replacement.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
else:
24+
n -= 1 # if '01' -1
25+
res += 1
26+
return res

0 commit comments

Comments
 (0)