Skip to content

Commit 78400f3

Browse files
authored
374. Guess Number Higher or Lower
1 parent 8b52b2f commit 78400f3

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

374.GuessNumberHigherorLower

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* The API guess is defined in the parent class.
3+
* @param num your guess
4+
* @return -1 if num is higher than the picked number
5+
* 1 if num is lower than the picked number
6+
* otherwise return 0
7+
* fun guess(num:Int):Int {}
8+
*/
9+
//https://leetcode.com/problems/guess-number-higher-or-lower/description/
10+
//Binary search: time O(log n)
11+
class Solution:GuessGame() {
12+
override fun guessNumber(n:Int):Int {
13+
var low = 1
14+
var high = n
15+
while(low <= high){
16+
val mid = low + (high - low)/2
17+
val guess = guess(mid)
18+
when(guess){
19+
0 -> return mid
20+
-1 -> high = mid -1
21+
1 -> low = mid + 1
22+
}
23+
}
24+
return -1
25+
}
26+
}

0 commit comments

Comments
 (0)