Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

猜数字大小 #34

Open
Aras-ax opened this issue Apr 17, 2019 · 0 comments
Open

猜数字大小 #34

Aras-ax opened this issue Apr 17, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Apr 17, 2019

我们正在玩一个猜数字游戏。 游戏规则如下:
我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。
每次你猜错了,我会告诉你这个数字是大了还是小了。
你调用一个预先定义好的接口guess(int num),它会返回 3 个可能的结果(-1,1 或 0):

  • -1 : 我的数字比较小
  • 1 : 我的数字比较大
  • 0 : 恭喜!你猜对了!
    示例 :
输入: n = 10, pick = 6
输出: 6

解答

function guessNumber(n) {
    let i = 0,
        l = n;
    while (i < l) {
        let mid = i + Math.floor((i - i) / 2),
            res = guess(mid);
        if (res === 0) {
            return mid;
        } else if (res === 1) {
            i = mid + 1;
        } else {
            l = mid;
        }
    }
    return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant