【LeetCode】69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

class Solution {
public:
    int mySqrt(int x) {
        if(x<=1) return x;
        long low = 1;
        long high = x;
        long mid;
        long tmp;
        while(low <high)
        {
            mid = (high+low)/2;
            tmp = mid * mid;
            if(tmp < x)
                low = mid +1;
            else if(tmp > x)
               high = mid-1;
               else if(tmp==x)
                return (int)mid;
        }
        return (int)((high*high)>x?high-1:high);
    }
};


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