991. Broken Calculator

Broken Calculator - LeetCode

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

  • code TLE bfs
class Solution:
    def brokenCalc(self, startValue: int, target: int) -> int:
        q = deque([startValue])
        visited = set()
        step = 0
        while q:
            for _ in range(len(q)):
                cur = q.popleft()
                if cur == target: return step
                if cur - 1 not in visited:
                    q.append(cur - 1)
                    visited.add(cur - 1)
                if cur * 2 not in visited:
                    q.append(cur * 2)
                    visited.add(cur * 2)
            step += 1

  • code
class Solution:
    def brokenCalc(self, startValue: int, target: int) -> int:
        ans = 0
        while target > startValue:
            ans += 1
            if target % 2: target += 1
            else: target //= 2

        return ans + startValue - target