leetcode: 69. x 的平方根
题目描述
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意: 不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
示例
输入: x = 4
输出: 2
解题思路
二分法找第一个小于等于x平方根的整数。
class Solution {
public int mySqrt(int x) {
int l = 0, r = x;
while (l <= r) {
int mid = (l + r) / 2;
long prod = (long) mid * mid;
if (prod == x) {
return mid;
}
else if (prod < x) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return r;
}
}
牛顿迭代法
显然,方程 的零点就是C的平方根。
求解方程f(x) = 0。
f(x)在x某个邻域的泰勒展开为
取前两项 的求解结果, 作为方程f(x) = 0的近似解。
牛顿迭代 ,迭代逼近近似解。
class Solution {
public int mySqrt(int x) {
long res = x;
while (res * res > x) {
res = (res + x / res) / 2;
}
return (int) res;
}
}