#991
Medium Algorithms Broken calculator
Math Greedy
55.9% acceptance
Feb 25, 2026
2836
216
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn broken_calc(start_value: i32, target: i32) -> i32 {
let mut ops = 0;
let mut t = target;
while t > start_value {
if t % 2 == 0 { t /= 2; } else { t += 1; }
ops += 1;
}
ops + start_value - t
}
}