-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrokenCalculator.java
More file actions
46 lines (43 loc) · 1.22 KB
/
Copy pathBrokenCalculator.java
File metadata and controls
46 lines (43 loc) · 1.22 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
//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.
//
//
//
//Example 1:
//
//Input: startValue = 2, target = 3
//Output: 2
//Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
//Example 2:
//
//Input: startValue = 5, target = 8
//Output: 2
//Explanation: Use decrement and then double {5 -> 4 -> 8}.
//Example 3:
//
//Input: startValue = 3, target = 10
//Output: 3
//Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
//
//
//Constraints:
//
//1 <= x, y <= 109
public class BrokenCalculator {
public int brokenCalc(int startValue, int target) {
int count = 0;
while (startValue < target) {
count++;
if (target % 2 != 0) target++;
else target /= 2;
}
return startValue - target + count;
}
public static void main(String[] args) {
BrokenCalculator bc = new BrokenCalculator();
System.out.println(bc.brokenCalc(5, 8));
}
}