
-Code
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is higher than the picked number
* 1 if num is lower than the picked number
* otherwise return 0
* int guess(int num);
*/
public class Solution extends GuessGame {
public int guessNumber(int n) {
long left = 1, right = n;
while(left <= right) {
int middle = (int) ((left + right) / 2);
// guess api를 이용해야함
int guessResult = guess(middle);
// 이진 탐색 시작
if (guessResult == 0) {
return middle;
} else if (guessResult == -1) {
right = middle - 1;
} else {
left = middle + 1;
}
}
return -1;
}
}
처음에 api를 이용해야 하는 문제임을 처음 접해서 이상하게 접근했습니다. api를 이용함을 알게 되니 쉽게 풀 수 있었습니다.
'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [LeetCode/Java] N-th Tribonacci Number (0) | 2025.12.31 |
|---|---|
| [백준/Java] 3018번 캠프파이어 (0) | 2025.12.31 |
| [LeetCode/Java] Search in a Binary Search Tree (0) | 2025.12.31 |
| [LeetCode/Java] Leaf-Similar Trees (0) | 2025.12.31 |
| [LeetCode/Java] Maximum Depth of Binary Tree (0) | 2025.12.31 |