Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

991. Broken Calculator 🌟🌟

There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:

Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.

Greedy Solution

Code

class Solution {
public:
    int brokenCalc(int startValue, int target) {
        int cnt = 0;
        while(target>startValue){
            if(target&1){
                target++;
            }else{
                target/=2;
            }
            cnt++;
        }
        return cnt + (startValue - target);
    }
};