LeetCode 991: Broken Calculator Solution

Master LeetCode problem 991 (Broken Calculator), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

991. Broken Calculator

Problem Explanation

Explanation:

To solve this problem, we can work backwards from the target to the startValue. At each step, we choose either to divide by 2 or add 1 based on whether the current number is even or odd. By doing this, we can reach the startValue from the target. The number of operations needed will be the minimum steps taken.

Algorithm:

  1. Initialize a variable result to 0.
  2. Iterate while target is greater than startValue:
    • If target is even, divide it by 2.
    • If target is odd, increment it by 1.
    • Increment result by 1.
  3. Add the difference between startValue and target to result.

Time Complexity:

The time complexity of this algorithm is O(log(target)).

Space Complexity:

The space complexity is O(1).

:

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 991 (Broken Calculator)?

This page provides optimized solutions for LeetCode problem 991 (Broken Calculator) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 991 (Broken Calculator)?

The time complexity for LeetCode 991 (Broken Calculator) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 991 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 991 in Java, C++, or Python.

Back to LeetCode Solutions