Problem : Implement
int sqrt(int x)
.
Compute and return the square root of x.
1.C++版(牛顿迭代公式)
class Solution {
public:
int sqrt(int x) {
double xi = 1.0;
while (abs(xi * xi - x) > 0.1) {
xi = (xi + x / xi) / 2;
}
return (int) xi;
}
};
2.Java版(牛顿迭代公式)
public class Solution {
public int sqrt(int x) {
double xi=1.0;
while(Math.abs(xi*xi-x*x)>0.1){
xi=(xi+x/xi)/2;
}
return (int) xi;
}
}