美文网首页
Guess Number Higher or Lower

Guess Number Higher or Lower

作者: BLUE_fdf9 | 来源:发表于2018-09-10 22:53 被阅读0次

    题目
    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):

    答案

    public class Solution extends GuessGame {
        public int guessNumber(int n) {
            int left = 1, right = n;
            while(left <= right) {
                int mid = left + (right - left) / 2;
                int ret = guess(mid);
                if(ret == 0) return mid;
                else if(ret == -1) {
                    // go left
                    right = mid;
                }
                else {
                    left = mid + 1;
                }
            }
            return 0;
        }
    }
    

    相关文章

      网友评论

          本文标题:Guess Number Higher or Lower

          本文链接:https://www.haomeiwen.com/subject/isuhgftx.html