All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0901_1000.s0991_broken_calculator.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0901_1000.s0991_broken_calculator;

// #Medium #Math #Greedy #2022_03_31_Time_0_ms_(100.00%)_Space_41.1_MB_(40.35%)

/**
 * 991 - Broken Calculator\.
 *
 * Medium
 *
 * 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 <= x, y <= 109
**/
public class Solution {
    public int brokenCalc(int startValue, int target) {
        int result = 0;
        while (startValue != target) {
            if (target > startValue && target % 2 != 0) {
                target += 1;
                result++;
            } else if (target > startValue) {
                target /= 2;
                result++;
            } else {
                result += startValue - target;
                break;
            }
        }
        return result;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy