LeetCode in Kotlin

991. Broken Calculator

Medium

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.

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:

Solution

@Suppress("NAME_SHADOWING")
class Solution {
    fun brokenCalc(startValue: Int, target: Int): Int {
        var target = target
        var 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
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy