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;
int left=1, right=x;
while(left<=right)
{
int mid=(left+right)/2;
if(mid==x/mid) return mid;
if(mid > x/mid) right=mid-1;
else left=mid+1;
}
return right;
}
};