原题网址:https://leetcode.com/problems/sqrtx/
Implement int sqrt(int x).
Compute and return the square root of x.
方法一:二分法。
public class Solution {
public int mySqrt(int x) {
int i=0, j=x;
while (i<=j) {
int m = (i+j)/2;
long m2 = (long)m*m;
if (m2==(long)x) return m;
if (m2>x) {
j = m - 1;
} else {
i = m + 1;
}
}
return i-1;
}
}
方法二:牛顿迭代法。
public class Solution {
public int mySqrt(int x) {
if (x == 0) return 0;
double y = Math.max(1, x/2);
while (true) {
double ny = (((double)y*y+x)/2/y);
if (Math.abs(y-ny) <= 0.01) return (int)ny;
y=ny;
}
}
}

本文介绍了两种求解LeetCode题目sqrt(x)的有效方法:二分查找法和牛顿迭代法。二分查找法通过不断缩小搜索范围来逼近答案;牛顿迭代法则利用数学原理逐步修正估算值直至满足精度要求。
830

被折叠的 条评论
为什么被折叠?



