topic
Implement int sqrt(int x)
functions. Computes and returns x square root, wherein x is a non-negative integer. Since the return type is an integer, only the integer part of the result is retained, and the decimal part will be discarded.
Example 1:
输入: 4
输出: 2
Example 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
- Binary search
class Solution{
public int mySqrt(int x){
if(x == 0 || x == 1){
return x;
}
int left = 1;
int right = x;
while(left < right){
int mid = left + (right-left)/2;
if (mid * mid > x){
right = mid - 1;
}else{
left = mid + 1;
}
}
return right;
}
}
mid = left + (right-left)/2
, Writing this way is afraid that left+right
if the value is too large in a strongly typed language , it may cross the boundary, so use this technique to deal with it.
- Newton iteration method
class Solution:
def mySqrt(self,x):
if x < 0 :
raise Exception('不能输入负数')
if x == 0:
return 0
#起始的时候在1,随意设置
cur = 1
while True:
pre = cur
cur = (cur + x / cur) / 2
if abs(cur-pre) < 1e-6:
return int(cur)
- Newton iteration to simplify the code
class Soluction(object):
def mySqrt(self,x):
r=x
while r*r>x:
r=(r+x/r)/2
return r