Skip to content

Commit ff8b64f

Browse files
authored
Create 0397 Integer Replacement.md
1 parent 8f03591 commit ff8b64f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

greedy/0397 Integer Replacement.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# 397. Integer Replacement
2+
https://leetcode-cn.com/problems/integer-replacement/
3+
Given a positive integer n, you can apply one of the following operations:
4+
If n is even, replace n with n / 2.
5+
If n is odd, replace n with either n + 1 or n - 1.
6+
Return the minimum number of operations needed for n to become 1.
7+
8+
Example 1:
9+
Input: n = 8
10+
Output: 3
11+
Explanation: 8 -> 4 -> 2 -> 1
12+
13+
Example 2:
14+
Input: n = 7
15+
Output: 4
16+
Explanation: 7 -> 8 -> 4 -> 2 -> 1
17+
or 7 -> 6 -> 3 -> 2 -> 1
18+
19+
Example 3:
20+
Input: n = 4
21+
Output: 2
22+
23+
Constraints:
24+
1 <= n <= 2^31 - 1
25+
26+
``` python3
27+
class Solution:
28+
def integerReplacement(self, n: int) -> int:
29+
ans=0
30+
while n!=1:
31+
if n%2==0:
32+
n//=2
33+
ans+=1
34+
elif n%4==1:
35+
n//=2
36+
ans+=2
37+
else:
38+
if n==3:
39+
n=1
40+
else:
41+
n=n//2+1
42+
ans+=2
43+
return ans
44+
```

0 commit comments

Comments
 (0)