LeetCode 69. Sqrt(x) 求平方根

296 阅读1分钟

leetcode.com/problems/sq…

Discuss:www.cnblogs.com/grandyang/p…

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

 

Example 1:

Input: x = 4
Output: 2

Example 2:

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

 

Constraints:

  • 0 <= x <= 231 - 1

解法一:

二分法求解。记得判断是否合法的时候要用 m == x / m,如果用 m * m > x 有可能会导致越界。

class Solution {
    fun mySqrt(x: Int): Int {
        if (x == 0 || x == 1) {
            return x
        }
        var result = 0
        var l = 0
        var r = x
        while (l <= r) {
            val m = (l + r) / 2
            if (m == x / m) {
                return m
            } else if (m > x / m) {
                r = m - 1
            } else if (m < x / m) {
                l = m + 1
                result = m
            }
        }
        return result
    }
}

解法二:

这道题还有另一种解法,是利用牛顿迭代法,可参见网友 Annie Kim's Blog的博客,因为要求 x2 = n 的解,令 f(x)=x2-n,相当于求解 f(x)=0 的解,可以求出递推式如下:

xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2

注意为了防止越界,声明为 Long 整型,参见代码如下:

class Solution {
    fun mySqrt(x: Int): Int {
        if (x == 0 || x == 1) {
            return x
        }
        var result: Long = x.toLong()
        while (result * result > x) {
            result = (result + x / result) / 2
        }

        return result.toInt()
    }
}