- Sqrt(x) II
Implement double sqrt(double x) and x >= 0.
Compute and return the square root of x.
Example
Given n = 2 return 1.41421356
Notice
You do not care about the accuracy of the result, we will help you to output results.
思路:
解法1: Binary Search。
注意:当x<1时,必须将其转换为1/x。
代码如下:
class Solution {
public:
/**
* @param x: a double
* @return: the square root of x
*/
double sqrt(double x) {
double result;
double start = 0, end, mid;
double origX = x;
if (x < 1) x = 1.0 / x;
end = x;
while(start + 1e-9 < end) {
mid = start + (end - start) / 2;
if (mid * mid < x) {
start = mid;
} else {
end = mid;
}
}
result = start + (end - start) / 2;
if (origX < 1) {
result = 1.0 / result;
}
return result;
}
};
解法2:
这题最快应该是用牛顿迭代法。下次再做。