[LeetCode] 107: Sqrt(x)

来源:互联网 发布:布拉格之春 知乎 编辑:程序博客网 时间:2024/06/04 19:39
[Problem]

Implement int sqrt(int x).

Compute and return the square root of x.


[Solution]
class Solution {
public:
int sqrt(int x) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// invalid
if(x <= 0)return 0;

// iterate
double a = 1, b = x/a;
while(fabs(b-a) > 0.00000001){
a = b;
b = (a + x/a)/2;
}
return b;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击