69. Implement int sqrt(int x).

78 阅读1分钟

题目描述

Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:
Input: 4
Output: 2

Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

解题思路: 2分暴力破解法

从0 开始判断, 更优化的方案是使用2分法, 设置left为0, right为x, mid 为 (left + right) / 2, 当mid 的平方大于x 时, 我们将right设置为mid,否则 将left 设置为mid, 一直循环到 left与right 相差1, 最后处理一下特殊值即可

示例代码

func mySqrt(_ x: Int) -> Int {
    if x < 2 {
        return x
    }
    var left = 0
    var right = x
    while left + 1 < right {
        let mid = (left + right) / 2

        if mid * mid > x {
            right = mid
        }else {
            left = mid
        }
    }
    return left
}