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 X, int Y) {
    int ops = 0;

    while (X < Y) {
      if (Y % 2 == 0)
        Y /= 2;
      else
        Y += 1;
      ++ops;
    }

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

    while (X < Y) {
      if (Y % 2 == 0)
        Y /= 2;
      else
        Y += 1;
      ++ops;
    }

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

    while X < Y:
      if Y % 2 == 0:
        Y //= 2
      else:
        Y += 1
      ops += 1

    return ops + X - Y