题目:
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num)
which returns 3 possible results (-1
, 1
, or 0
):
-1 : My number is lower 1 : My number is higher 0 : Congrats! You got it!
Example:
n = 10, I pick 6. Return 6.
题意:
给定数字n和某个在1-n之间的位置数x,系统已经定义好了函数guess(),当guess(x)返回0,则猜中,当guess(x)返回-1,则你猜的数字比给定的数字大了,当guess(x)返回1,则你猜的数字比给定的数字小了了,写一个函数来猜数字,返回给定的需要猜的那个数字
代码:
# 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 = 1
high = n
while guess((low+high)/2) != 0 and low < high : #如果没猜中且low<high,则继续循环来猜
if guess((low+high)/2) == -1 : #你猜的数字猜高了,将high降低
high = (low+high)/2 - 1
else :
if guess((low+high)/2) == 1 : #你猜的数字猜低了,将low升高
low = (low+high)/2 + 1
return (low+high)/2
笔记:
这类题的下标变换,老是需要用调试代码才能理清楚
if guess((low+high)/2) == 1 : #你猜的数字猜低了,将low升高
low = (low+high)/2 + 1
此处,如果改成 low = (low+high)/2 ,则会进入死循环(例如n=2,给定2,则low总是1)
调试了之后,才知道要写成low = (low+high)/2+1(排除 (low+high)/2仍等于low或high的情况,避免进入死循环)