Skip to content

Commit b93ca38

Browse files
authored
Merge pull request #89 from suburban-daredevil/guess-number
374 | Added code for guess number higher or lower problem
2 parents 55e5e2f + a8f35d1 commit b93ca38

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

374/README.md

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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.

374/guessNumberHigherOrLower.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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

0 commit comments

Comments
 (0)