69. Sqrt(x)
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sqrtx
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
公式
class Solution {
public int mySqrt(int x) {
int ans = (int) Math.exp(0.5 * Math.log(x));
return 1L * (ans + 1) * (ans + 1) <= x ? ans + 1 : ans;
}
}
二分
class Solution {
public int mySqrt(int x) {
int l = 0, r = x;
int ret = 0;
while (l <= r) {
int mid = l + (r - l) / 2;
if (1L * mid * mid <= x) {
ret = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ret;
}
}
牛顿迭代

class Solution {
public int mySqrt(int x) {
if (x == 0) {
return 0;
}
double C = x, x0 = x;
while (true) {
double xi = 0.5 * (x0 + C / x0);
if (Math.abs(x0 - xi) < 1e-7) {
break;
}
x0 = xi;
}
return (int) x0;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号