File tree 2 files changed +51
-0
lines changed
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## Guess Number Higher or Lower
2
+
3
+ We are playing the Guess Game. The game is as follows:
4
+
5
+ I pick a number from 1 to n. You have to guess which number I picked.
6
+
7
+ Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
8
+
9
+ You call a pre-defined API int guess(int num), which returns 3 possible results:
10
+
11
+ -1: The number I picked is lower than your guess (i.e. pick < num).
12
+ 1: The number I picked is higher than your guess (i.e. pick > num).
13
+ 0: The number I picked is equal to your guess (i.e. pick == num).
14
+ Return the number that I picked.
Original file line number Diff line number Diff line change
1
+ # The guess API is already defined for you.
2
+ # @param num, your guess
3
+ # @return -1 if my number is lower,
4
+ # 1 if my number is higher, otherwise return 0
5
+
6
+ # this function is just added to pass the flake8 code linter
7
+ # delete this function definition while using it on leetcode
8
+ def guess (num : int ) -> int :
9
+ pass
10
+
11
+
12
+ class Solution :
13
+ def guessNumber (self , n : int ) -> int :
14
+ # here start = 1 ans end = n
15
+ # I supply mid as my pick and check with the original pick
16
+ # if pick is not right, update start or end accodingly
17
+
18
+ start = 1
19
+ end = n
20
+ while start <= end :
21
+
22
+ mid = start + (end - start ) // 2
23
+ x = guess (mid )
24
+
25
+ if x == 0 :
26
+ # element is found
27
+ return mid
28
+
29
+ elif x == - 1 :
30
+
31
+ # guessed element is greater than actual element
32
+ # search in the left of mid
33
+ end = mid - 1
34
+ else :
35
+ # guessed element is less than actual element
36
+ # search in the right of mid
37
+ start = mid + 1
You can’t perform that action at this time.
0 commit comments