题目
Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
分析
牛顿迭代法
res = (res + x / res) / 2;
二分法
最重要的时不要超出int的范围,使用x > s/x进行判断
public static int mySqrt(int x) {
if (x == 0) return 0;
double last = 0;
double res = 1;
while (res != last)
{
last = res;
res = (res + x / res) / 2;
}
return (int)(res);
}