如果x<1,那么sqrt(x)是>x的。在这种情况下我们把end设为1
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) throw new IllegalArgumentException();
double left = 0.0;
double right = x;
double error = 1e-12;
if (right < 1.0) right = 1.0;
double mid;
while (right - left > error) {
mid = left + (right - left) / 2;
if (mid * mid == x) return mid;
if (mid * mid > x) right = mid;
else left = mid;
}
return left;
}
}
No comments:
Post a Comment