题目
实现 int sqrt(int x) 函数。计算并返回 x 的平方根,其中 x 是非负整数。由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
备注
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sqrtx
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法1
一步步往前,效率并不高
class Solution {
public int mySqrt(int x) {
if (x < 2) {
return x;
}
int pre = 2;
int result = x / pre;
while (result > (pre + 1)) {
result = x / ++pre;
}
return Math.min(pre, result);
}
}
解法2
主要是看别人的答案,用的是二分法,时间效率比较快。
解法3
与解法2区别,用除法,避免使用long(x过大时),收敛更快(能快多少,不太清楚了)
class Solution {
public int mySqrt(int x) {
int left = 0;
int right = (x >>> 1) + 1;
while (left < right) {
int mid = (left + right + 1) >>> 1;
int midOther = x / mid;
if (Math.abs(midOther - mid) < 2) {
return Math.min(mid, midOther);
}
if (midOther > mid) {
left = mid;
if (right > midOther - 1) {
right = midOther - 1;
}
} else {
right = mid - 1;
if (left < midOther) {
left = midOther;
}
}
}
return left;
}
}