Implement double
sqrt(double x)
and x >= 0
.
Compute and return the square root of x.
Notice
You do not care about the accuracy of the result, we will help you to output results.
Example
Given n
= 2
return 1.41421356
计算时,需要注意小数的计算,当开方的数是小数时,将end的默认值定义为0;
java
public class Solution {
/*
* @param x: a double
* @return: the square root of x
*/
public double sqrt(double x) {
// write your code here
if (x < 0) {
return -1;
}
double start = 0;
double end = x;
if (end < 1) {
end = 1;
}
double mid = 0;
double eps = 1e-12;
while (end - start > eps) {
mid = (end - start) / 2 + start;
if (mid * mid > x) {
end = mid;
} else {
start = mid;
}
}
return start;
}
}