[LeetCode] Broken Calculator

991. Broken Calculator

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int brokenCalc(int X, int Y) {
int res = 0;
while(Y > X) {
if(Y&1) Y += 1;
else Y>>=1;
res++;
}
return res + X - Y;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/23/PS/LeetCode/broken-calculator/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.