//#69 Sqrt(x)
//8ms 100%
class Solution {
public:
int mySqrt(int x)
{
//x is guarantted to be valid
//x has to be equal or larger than 0
if(x == 0) return 0;
if(x < 4) return 1;
int m = x/2 + 1;
if(m > 46341) m = 46341;
int n = 0;
while(true)
{
int k = (m+n)/2;
//cout << "k == " << k << endl;
if(k*k <= x)
{
if(k <= 46339)
{
if((k+1)*(k+1) > x)
{
return k;
}
}
else
{
return k;
}
}
if(k*k > x) { m = k; }
else { n = k; }
}
assert(0);
}
};
[Leetcode]#69 Sqrt(x)
最新推荐文章于 2024-11-17 18:49:52 发布