题目描述:
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.
要完成的函数:
int guess(int num);//api函数
int guessNumber(int n)
说明:
1、给定一个整数 n,从1到n中挑一个数出来,让你猜是哪个数。每次你猜一个数,调用一次api函数,返回0就代表刚好是这个数,你猜对了!如果返回-1,就表示你猜的数太大了,实际的数比这个小。如果返回1,就表示你猜的数太小了,实际的数比这个大。要求最终返回对的那个数。
2、这道题很明显是一道二分查找的题目,手工写一个二分查找的代码。
代码如下:(附详解)
int guess(int num); int guessNumber(int n) { int low=1,high=n,mid,t; while(low<=high) { mid=low+(high-low)/2;//写成 mid=(low+high)/2 可能会上溢 t=guess(mid); if(t==0) return mid; else if(t==-1)//实际的数比mid小 high=mid-1; else //实际的数比mid大 low=mid+1; } }
上述代码实测2ms,beats 100.00% of cpp submissions。
原文地址:https://www.cnblogs.com/king-3/p/9125248.html
时间: 2025-01-19 13:17:55