Problem:
Implement int sqrt(int x)
.
Compute and return the square root of x.
牛顿迭代法。class Solution {
public:
int sqrt(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
assert(x >= 0);
if (x == 0) return 0;
double val = x;
double last;
do
{
last = val;
val = (val + x/val)/2.0;
}while(abs(val-last) > 0.000001);
return val;
}
};