LeetCode:Sqrt(x)

Sqrt(x)



Total Accepted: 94989  Total Submissions: 373552  Difficulty: Medium

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question

Hide Tags
  Binary Search Math
Hide Similar Problems
  (M) Pow(x, n)
















思路:二分查找。

如:x = 10

1 2 3 4 5 6 7 8 9 10

设:left = 1,right = 10,则 mid = (1+10)/2 = 5

由于mid * mid > x * x,则right = mid;这时,left = 1,right = 5,mid = (1+5)/2 = 3;

由于mid * mid <= x * x,则left = mid;这时,left = 3,right = 5,mid = (3+5)/2 = 4;

由于mid * mid > x * x,则right = mid;这时,left = 3,right = 4,mid = (3+4)/2 = 3;

由于 left + 1 == right,break;

返回结果:left = 3;



c++ code:

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


你可能感兴趣的:(LeetCode,Sqrtx)