Implement int sqrt(int x)
.
int sqrt(int x) {
if (x < 0) return -1;
int start = 0;
int end = x;
if (x == 0 || x == 1) return x;
while (start <= end) {
int mid = start + (end - start) / 2;
if ((mid + 1) > x / (mid + 1) && (mid <= x / mid) ) {
return mid;
} else if (mid < x / mid) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
Implement double
sqrt(double x)
public double sqrt(double x) {
if (x < 0) return -1;
double left = 0;
double right = (x < 1) ? 1 : x;
double maxDiff = 0.000001;
do {
double mid = left + (right - left) / 2;
if (Math.abs(x - mid * mid) <= maxDiff) {
return mid;
} else if (x - mid * mid < 0) {
right = mid;
} else {
left = mid;
}
} while (true);
}
.