Implement
int sqrt(int x)
.
Compute and return the square root of x.
<pre class="prettyprint linenums:1"><code class="language-cpp">
int sqrt(int x) {
int b = 0;
int e = x/2 + 1;
while(b <= e)
{
long long mid= (b+e)/2;
long long sl = mid * mid;
long long sh = (mid+1) * (mid+1);
if (sl <= x && sh > x)
return mid;
else if (sl < x)
b = mid + 1;
else
e = mid - 1;
}
return -1;
}
</code></pre>
No comments:
Post a Comment