991. Broken Calculator LeetCode Solution
In this guide, you will get 991. Broken Calculator LeetCode Solution with the best time and space complexity. The solution to Broken Calculator problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Broken Calculator solution in C++
- Broken Calculator solution in Java
- Broken Calculator solution in Python
- Additional Resources
Problem Statement of Broken Calculator
There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:
multiply the number on display by 2, or
subtract 1 from the number on display.
Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.
Example 1:
Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:
Input: startValue = 5, target = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3:
Input: startValue = 3, target = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Constraints:
1 <= startValue, target <= 109
Complexity Analysis
- Time Complexity:
- Space Complexity:
991. Broken Calculator LeetCode Solution in C++
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;
}
};
/* code provided by PROGIEZ */
991. Broken Calculator LeetCode Solution in Java
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;
}
}
// code provided by PROGIEZ
991. Broken Calculator LeetCode Solution in Python
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
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.