# 【Leetcode】374. Guess Number Higher or Lower【二分搜索】

### 374. Guess Number Higher or Lower

• Total Accepted: 17904
• Total Submissions: 56954
• Difficulty: Easy

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.


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

public class Solution extends GuessGame {
public int guessNumber(int n) {
return guessRange(1,n);
}
public int guessRange(int start,int end){
if(start==end){
return start;
}
int middle=start/2+end/2+(start%2+end%2)/2;
int ans=guess(middle);
if(ans==0){
return middle;
}
if(ans>0){
return guessRange(middle+1,end);
}
return guessRange(start,middle-1);
}
}

• 本文已收录于以下专栏：

## [leetcode] 374. Guess Number Higher or Lower 解题报告

• qq508618087
• 2016年07月16日 03:13
• 2191

## LeetCode 374. 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 g...
• y12345678904
• 2016年07月13日 16:06
• 1321

## Leetcode 374. Guess Number Higher or Lower 桌游猜数字 解题报告

1 解题思想这道题就我们平常玩的最多的猜数字。。它内置了一个方法，可以告诉你数字是大是小。。其实也就是二分法。。没啥好说的2 原题We are playing the Guess Game. The ...
• MebiuW
• 2016年07月13日 15:35
• 1685

## leetcode 375. Guess Number Higher or Lower II 解题小结

• 2016年07月19日 02:08
• 2573

## Leetcode题解 374. 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 gue...
• Xd_Yu
• 2016年07月16日 23:33
• 721

## 关于LeetCode中Guess Number Higher or Lower一题的理解

• zsy112371
• 2016年09月08日 13:52
• 704

## 375. Guess Number Higher or Lower II

We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to g...
• wdlsjdl2
• 2016年07月18日 15:23
• 1245

## LeetCode—375. Guess Number Higher or Lower II

Guess Number Higher or Lower II思路：刚开始的时候想到的不是动态规划，而是在（s,e）的范围内求出m,使得（s,m-1）=(m+1,e),结果发现两个问题，一个是不能使得...
• corpsepiges
• 2016年07月18日 17:09
• 1677

## [Leetcode]374. 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 ...
• sunhero2010
• 2016年07月14日 21:45
• 105

## 374. 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 g...
• alwaystry
• 2016年08月07日 16:45
• 182

举报原因： 您举报文章：【Leetcode】374. Guess Number Higher or Lower【二分搜索】 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)