Skip to content

991. Broken Calculator 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int brokenCalc(int startValue, int target) {
    int ops = 0;

    while (startValue < target) {
      if (target % 2 == 0)
        target /= 2;
      else
        ++target;
      ++ops;
    }

    return ops + startValue - target;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int brokenCalc(int startValue, int target) {
    int ops = 0;

    while (startValue < target) {
      if (target % 2 == 0)
        target /= 2;
      else
        ++target;
      ++ops;
    }

    return ops + startValue - target;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def brokenCalc(self, startValue: int, target: int) -> int:
    ops = 0

    while startValue < target:
      if target % 2 == 0:
        target //= 2
      else:
        target += 1
      ops += 1

    return ops + startValue - target