Implement int sqrt(int x)
.
Compute and return the square root of x.
求x的平方根。
2分没甚么好说的,注意INT_MAX溢出的情况!
class Solution {
public:
int mySqrt(int x) {
long long l=0,r=x,mid;
while(l<=r)
{
mid=(l+r)>>1;
long long ans=mid*mid;
if(ans<=x && (mid+1)*(mid+1)>x)
return mid;
if(ans>x)
r=mid⑴;
else
l=mid+1;
}
return mid;
}
};