开方取整函数
c++:
class Solution {
public:
int mySqrt(int x) {
//return floor(sqrt(x)); // c++ 开方 取整 函数 也可以
return int(sqrt(x));
}
};
python
class Solution:
def mySqrt(self, x: int) -> int:
#return floor(sqrt(x)) # 开方 取整 函数 也可以
return int(sqrt(x))
二分查找:
结果只保留整数的部分,小数部分将被舍去。说明找到的 ans*ans <= x
class Solution {
public:
int mySqrt(int x) {
int l=0,r=x,ans=0;
while(l<=r){
int mid = (l+r)/2;
if((long long) mid*mid == x ){ // long long (__int64)
return mid;
}else if ( (long long)mid*mid <= x ){
ans = mid; //ans*ans <= x
l = mid + 1;
}else{
r = mid - 1;
}
}
return ans;
}
};
python
class Solution:
def mySqrt(self, x: int) -> int:
l,r,ans = 0,x,0
while l<=r:
mid = (l+r)//2 # python 整除
if mid*mid <=x:
ans = mid
l = mid +1
else:
r = mid -1
return ans