Broken Calculator

medium greedy math bit manipulation

Problem

There is a broken calculator that has the integer startValue on its display initially. In one operation, you can either multiply the number on the display by 2, or subtract 1 from it. Given two integers startValue and target, return the minimum number of operations needed to display target.

InputstartValue = 2, target = 3
Output2
Use double then decrement: 2 → 4 → 3. That is 2 operations.

def broken_calc(startValue, target):
    ops = 0
    while target > startValue:
        if target % 2 == 0:
            target //= 2
        else:
            target += 1
        ops += 1
    return ops + (startValue - target)
function brokenCalc(startValue, target) {
  let ops = 0;
  while (target > startValue) {
    if (target % 2 === 0) target /= 2;
    else target += 1;
    ops += 1;
  }
  return ops + (startValue - target);
}
class Solution {
    public int brokenCalc(int startValue, int target) {
        int ops = 0;
        while (target > startValue) {
            if (target % 2 == 0) target /= 2;
            else target += 1;
            ops += 1;
        }
        return ops + (startValue - target);
    }
}
int brokenCalc(int startValue, int target) {
    int ops = 0;
    while (target > startValue) {
        if (target % 2 == 0) target /= 2;
        else target += 1;
        ops += 1;
    }
    return ops + (startValue - target);
}
Time: O(log target) Space: O(1)