forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0991-broken-calculator.js
More file actions
34 lines (31 loc) · 832 Bytes
/
0991-broken-calculator.js
File metadata and controls
34 lines (31 loc) · 832 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 991. Broken Calculator
* https://leetcode.com/problems/broken-calculator/
* Difficulty: Medium
*
* There is a broken calculator that has the integer startValue on its display initially.
* In one operation, you can:
* - multiply the number on display by 2, or
* - subtract 1 from the number on display.
*
* Given two integers startValue and target, return the minimum number of operations needed
* to display target on the calculator.
*/
/**
* @param {number} startValue
* @param {number} target
* @return {number}
*/
var brokenCalc = function(startValue, target) {
let operations = 0;
let current = target;
while (current > startValue) {
if (current % 2 === 0) {
current = current / 2;
} else {
current++;
}
operations++;
}
return operations + startValue - current;
};