티스토리 뷰
Problem
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 <= 10^9
Solution
고장난 계산기가 있는데 처음 값에서 곱하기 2나 빼기 1만 동작합니다.
시작 값과 타겟 값이 주어질 때 타겟 값을 만들 수 있는 최소 연산 횟수를 구하는 문제입니다.
재귀호출을 이용해 해결할 수 있습니다.
public class Solution {
public int brokenCalc(int startValue, int target) {
if (startValue == target) { // (1)
return 0;
}
if (startValue > target) { // (2)
return startValue - target;
}
if (target % 2 == 0) { // (3)
return 1 + brokenCalc(startValue, target / 2);
}
return 1 + brokenCalc(startValue, target + 1); // (4)
}
}
- 두 수가 같을 땐 0을 반환합니다.
startValue
가 더 클 땐 -1로만target
을 만들 수 있으므로startValue
에서target
값을 빼서 반환합니다.target
이 2의 배수인 경우target
을 2로 나눠 재귀호출 합니다. 1회 연산이 수행되었기 때문에 1을 더해 반환합니다.target
이 2의 배수가 아닌 경우target
에 1을 더해 재귀호출합니다. 1회 연산이 수행되었기 때문에 1을 더해 반환합니다.
Test
package io.lcalmsky.leetcode.broken_calculator;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void testAll() {
assertAll(
() -> test(2, 3, 2),
() -> test(5, 8, 2),
() -> test(3, 10, 3)
);
}
private void test(int startValue, int `target`, int expected) {
// when
Solution solution = new Solution();
int actual = solution.brokenCalc(startValue, target);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
81. Search in Rotated Sorted Array II (0) | 2022.04.28 |
---|---|
700. Search in a Binary Search Tree (0) | 2022.04.27 |
289. Game of Life (0) | 2022.04.25 |
856. Score of Parentheses (0) | 2022.04.24 |
31. Next Permutation (0) | 2022.04.23 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- spring boot jwt
- Jackson
- 함께 자라기 후기
- Java
- 스프링부트
- gRPC
- QueryDSL
- spring boot application
- 알고리즘
- 헥사고날 아키텍처
- @ManyToOne
- 스프링 부트 회원 가입
- Spring Data JPA
- r
- 함께 자라기
- Spring Boot Tutorial
- JSON
- 클린 아키텍처
- Spring Boot JPA
- Spring Boot
- spring boot app
- intellij
- leetcode
- 스프링 부트 튜토리얼
- JPA
- 스프링 부트 애플리케이션
- proto3
- 스프링 데이터 jpa
- Linux
- 스프링 부트
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
글 보관함