LeetCode 69.Sqrt(x)

题目:

Implement int sqrt(int x).

Compute and return the square root of x.

分析与解答:更快的方法是牛顿法,这里采用二分法也是可以的。

class Solution {
public:
    int sqrt(int x) {
        if(x == 0){
            return 0;
        }
        int left = 1,right = x;
        while(left < right - 1){
            int mid = left + (right - left)/2;
            if((long long)mid*(long long)mid > x){
                right = mid;
            }else if((long long)mid*(long long)mid < x){
                left = mid;
            }else{
                return mid;
            }
        }
        return left;
    }
};



你可能感兴趣的:(LeetCode 69.Sqrt(x))