题目描述
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
思路
思路一
直接使用Math.sqrt()函数,对结果取整
思路二
使用牛顿法,迭代公式为:
A为x0的值
代码
代码一
public class Sqrt {
public int mySqrt(int x) {
return (int)Math.sqrt(x);
}
}
代码二
public class Sqrt2 {
public int mySqrt(int x) {
long xn = x;
while(xn * xn > x)
{
xn = (xn + x / xn) / 2;
}
return (int)xn;
}
}