Standard binary search in Python


  • 2

    Took me 10s.

    class Solution(object):
        def guessNumber(self, n):
            """
            :type n: int
            :rtype: int
            """
            l, r = 1, n
            while l + 1 < r:
                m = l + (r - l) / 2
                res = guess(m)
                if res < 0:
                    r = m
                elif res > 0:
                    l = m
                else:
                    return m
                    
            if guess(l) == 0:
                return l
            if guess(r) == 0:
                return r
            return None
    

  • 0
    E

    @jedihy , clean solution. Could you explain who to ensure m is an integer throughout the iterative process?


  • 0

    @enaj_25 No float number will be generated during the entire program. "divide" operation would not give a float number.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.