본문 바로가기
Programming/LeetCode

[LeetCode] Broken Calculator

by 데이터현 2022. 3. 23.

https://leetcode.com/problems/broken-calculator/

 

Broken Calculator - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

자꾸 풀라고 알람이 와서 풀어버리겠다!!

2를 곱하거나 1을 빼거나 해서 최소 횟수로 target 만들기

첫 풀이

class Solution:
    def brokenCalc(self, startValue: int, target: int) -> int:
        q : Deque = collections.deque()
        q.append((startValue, 0))
        while q:
            now, count = q.popleft()
            if now == target:
                return count
            else:
                if now < target:
                    q.append((now*2, count+1))
                if now-1 > 0:
                    q.append((now-1, count+1))

처음엔 최소? BFS? 라고 생각하고 풀었는데, 이렇게 BFS로 풀면 메모리 이슈가 있다.

 

비트 연산 풀이

class Solution:
    def brokenCalc(self, startValue: int, target: int) -> int:
        if startValue >= target:
            return startValue-target
        count = 0
        while target > startValue:
            # 2 나머지 있을 때
            if target & 1:
                target += 1
                count += 1
            target >>= 1
            count += 1
        count += startValue-target
        return count

'Programming > LeetCode' 카테고리의 다른 글

[LeetCode] Add Two Numbers  (0) 2022.03.23
[LeetCode] Reverse Linked List  (0) 2022.03.23
[LeetCode] Merge Two Sorted Lists  (0) 2022.03.23
[LeetCode] Palindrome Linked List  (0) 2022.03.23
[LeetCode] Reverse String  (0) 2022.02.28

댓글