其他分享
首页 > 其他分享> > iOS LeetCode ☞ 猜数字大小

iOS LeetCode ☞ 猜数字大小

作者:互联网

猜数字游戏的规则如下:

你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-110):

返回我选出的数字。

示例 1:

输入:n = 10, pick = 6
输出:6

示例 2:

输入:n = 1, pick = 1
输出:1

示例 3:

输入:n = 2, pick = 1
输出:1

示例 4:

输入:n = 2, pick = 2
输出:2

提示:

解题思路

二分法

代码

	// 374. 猜数字大小
    /**
     * Forward declaration of guess API.
     * @param  num -> your guess number
     * @return          -1 if the picked number is lower than your guess number
     *                  1 if the picked number is higher than your guess number
     *               otherwise return 0
     * func guess(_ num: Int) -> Int
     */
    func guessNumber(_ n: Int) -> Int {
        var left = 1, right = n
        while left < right {
            let mid = (left + right) / 2
            let guessNum = guess(mid)
            if guessNum == 0 {
                return mid
            } else if guessNum == -1 {
                left = mid + 1
            } else {
                right = mid - 1
            }
        }
        return left
    }

标签:guess,数字,iOS,number,mid,pick,LeetCode,left
来源: https://blog.csdn.net/LiqunZhang/article/details/121034738