Leetcode 69 Sqrt(x)
來源:程序員人生 發布時間:2017-01-12 12:00:01 閱讀次數:2976次
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;
}
};
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈