class Solution:
def mySqrt(self, x: int) -> int:
return self.find(0,x,x)
def find(self,left,right,target):
if target==0 or target==1:
return target
while left<right:
mid = left + (right - left) // 2
if mid*mid<=target and (mid+1)*(mid+1)>target:
return mid
elif (mid+1)*(mid+1)<=target:
left=mid+1
else:
right=mid
注意,Java中用 x/m<m
而不是m*m>x
防止溢出
- 如果这个整数的平方 严格大于 输入整数,那么这个整数肯定不是我们要找的那个数;
- 如果这个整数的平方 小于等于 输入整数,那么这个整数 可能 是我们要找的那个数
class Solution {
public int mySqrt(int x) {
return find(x,0,x);
}
public int find(int x,int left,int right){
if (x==1 || x==0){
return x;
}
while(left<right){
int mid=(left+right)/2;
if(mid<=x/mid && (mid+1)>x/(mid+1)){
return mid;
}else if(mid>x/mid){
right=mid;
}else{
left=mid+1;
}
}
return 0;
}
}
限制精度,比如小数点后10位:
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:
return x
left, right = 1, x
while left < right:
mid = left + (right - left) / 2
if mid * mid <= x and (mid + 1e-7) * (mid + 1e-7) > x:
return mid
elif mid * mid > x:
right = mid
else:
left = mid + 1e-7
补充:实现double_sqrt()函数
牛顿迭代法
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:
return 0
C, x0 = float(x), float(x)
while True:
xi = 0.5 * (x0 + C / x0)
if abs(x0 - xi) < 1e-7:
break
x0 = xi
return x0