69. Sqrt(x)【leetcode解题报告】

description

Implement int sqrt(int x).

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

思路

二分法,对于一个非负数n,它的平方根不会大于(n/2+1)。在[0, n/2+1]这个范围内可以进行二分搜索,求出n的平方根。

class Solution {
public:
    // 注:在中间过程计算平方的时候可能出现溢出,所以用long long。
    // E.G.:2147395599
    int mySqrt(int x) {
        long long res=x;
        long long  left = 0,right=x/2+1;
        while(left<right){
            long long  mid = (left+right)/2;
            long long  mul = mid*mid;
            if(mul==x){
                return mid;
            }
            if(mul>x){
                right = mid-1;
            }else{
                left = mid+1;
            }
        }
        return left*left>x?left-1:left;
    }
};

思路2

牛顿迭代法!参考博客:
http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

猜你喜欢

转载自blog.csdn.net/tan_change/article/details/80148107