# LeetCode 374. Guess Number Higher or Lower

## Description

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 :

Input: n = 10, pick = 6

Output: 6

## 描述

-1 : 我的数字比较小

1 : 我的数字比较大

0 : 恭喜！你猜对了！

### 思路

• 使用二分法，left 表示左边界，right 表示右边界。
• num 为中间值，如果 num 大于要猜的值，将 right 置为 num - 1；如果 num 小于要猜的值，将 left 置为 num + 1。

# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-06-28 16:24:44
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 1, n
num = left + ((right - left) >> 1)
res = guess(num)
if res == 0: return num
while res:
if res == 1:
left = num + 1
if res == -1:
right = num - 1
num = left + ((right - left) >> 1)
res = guess(num)
return num

|
10月前
|

Leetcode 313. Super Ugly Number

88 1
|
jenkins 持续交付

153 0
|
3月前
|

LeetCode 题目 65：有效数字（Valid Number）【python】
LeetCode 题目 65：有效数字（Valid Number）【python】
41 5
|
4月前
|

【LeetCode力扣】单调栈解决Next Greater Number（下一个更大值）问题
【LeetCode力扣】单调栈解决Next Greater Number（下一个更大值）问题
31 0
|
10月前
|

Leetcode Single Number II （面试题推荐）

33 0
|

LeetCode 414. Third Maximum Number

85 0
|

LeetCode 405. Convert a Number to Hexadecimal

80 0
|
API
LeetCode 375. Guess Number Higher or Lower II

99 0
|

LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
107 0
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
85 0