Skip to content

Commit e97c189

Browse files
committed
Add solution #397
1 parent 0faef5e commit e97c189

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@
315315
394|[Decode String](./0394-decode-string.js)|Medium|
316316
395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium|
317317
396|[Rotate Function](./0396-rotate-function.js)|Medium|
318+
397|[Integer Replacement](./0397-integer-replacement.js)|Medium|
318319
399|[Evaluate Division](./0399-evaluate-division.js)|Medium|
319320
404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy|
320321
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|

solutions/0397-integer-replacement.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* 397. Integer Replacement
3+
* https://leetcode.com/problems/integer-replacement/
4+
* Difficulty: Medium
5+
*
6+
* Given a positive integer n, you can apply one of the following operations:
7+
* 1. If n is even, replace n with n / 2.
8+
* 2. If n is odd, replace n with either n + 1 or n - 1.
9+
*
10+
* Return the minimum number of operations needed for n to become 1.
11+
*/
12+
13+
/**
14+
* @param {number} n
15+
* @return {number}
16+
*/
17+
/**
18+
* @param {number} n
19+
* @param {number} count
20+
* @return {number}
21+
*/
22+
var integerReplacement = function(n, count = 0) {
23+
if (n === 1) return count;
24+
if (n % 2 === 0) {
25+
return integerReplacement(n / 2, count + 1);
26+
} else {
27+
return Math.min(integerReplacement(n + 1, count + 1), integerReplacement(n - 1, count + 1));
28+
}
29+
};

0 commit comments

Comments
 (0)