We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8b52b2f commit 78400f3Copy full SHA for 78400f3
374.GuessNumberHigherorLower
@@ -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