Leetcode - Guess Number Higher or Lower

题目链接

Guess Number Higher or Lower

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.

解题思路

TODO (稍后补充)

解题代码

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        int myGuessNum = 1 + (n-1)/2;
        int begin = 1;
        int end = n;
        while(1) {
            int tip = guess(myGuessNum);
            if (tip == 0) break;
            if (tip < 0) {
                end = myGuessNum-1;
                myGuessNum = begin + (end - begin)/2;
                //myGuessNum = (begin + end)/2;
            }
            else {
                begin = myGuessNum+1;
                myGuessNum = begin + (end - begin)/2;
                //myGuessNum = (begin + end)/2;
            }
        }
        return myGuessNum;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,868评论 0 23
  • 1今天的故事是一首啊傻自己写的小诗,外加一些微不足道却特别想道的啊傻个人对诗的见解,啊傻希望不要写超过800字,毕...
    williamhyw阅读 3,429评论 2 6
  • July干了一整天繁重的脑力劳动,感觉脑浆都被炸空了,头轻脚重的下了车,想赶紧回房间沉到浴缸底去。刚刚进到大堂,J...
    旺财杨子阅读 631评论 1 50
  • 每个人来到这世上,无不孤独着生,孤独着死,在我们的人生道路上,虽然会出现许许多多的人,但每个人都只能是我们人生中的...
    晨夏千夜阅读 344评论 0 1
  • 阳光擦洗过的天空 几朵悠闲的白云 高高漂泊 从子夜出发 越过灰尘的城市 抵达一面 澄净着等待的湖水 并且不泛起一丝...
    杨昊田阅读 443评论 16 21