Leetcode: Guess number higher or lower done

Rachit Gupta
1 min readDec 27, 2016

--

This is a simple application of binary search. We are given the upper bound as input and lower bound is 1. Think of it as a sorted list from 1 to n i.e. [1,2,3..,n] and instead of a matching with a target number we can call the guess api.

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
low, high = 1, n + 1
mid = (low + high) / 2
val = guess(mid)
while val != 0:
if val == 1:
low = mid
if val == -1:
high = mid
mid = (low + high) / 2
val = guess(mid)
return mid

--

--