首页 > 代码库 > LeetCode--Sqrt(x)

LeetCode--Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

二分查找法:

class Solution {
public:
    int sqrt(int x) 
    {
        int high = INT_MAX;
        int low = 0;
        while(low <=high)
        {
            long long mid = (low+high)/2;
            long long temp = mid*mid;
            if(temp == x)
                return mid;
            else if(temp < x)
                low = mid+1;
            else
                high = mid-1;
        }
        return high;
    }
};

牛顿迭代法待续

LeetCode--Sqrt(x)