Implement int sqrt(int x)
.
Compute and return the square root of x.
public int sqrt(int x) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
if (x <= 0) {
return 0;
}
double pre = -1.0;
double cur = 1.0;
while (Math.abs(pre - cur) > 0.00001) {
pre = cur;
cur = (cur + x / cur) / 2;
}
return (int) cur;
}