X的平方根
作者:互联网
思路:二分查找 左边界暂为0 右边界暂为x
两个特殊 0的平方根为0 1的平方根为1
找到最逼近的mid mid*mid<=x
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
if(x==0||x==1){return x}
let left = 0;
let right = x;
let res;
//二分查找经典while(left<=right)
while(left<=right){
let mid = Math.floor((left+right)/2)
if(mid*mid<=x){
res = mid;
left = mid+1;
}else{
right = mid-1;
}
}
return res
}
标签:right,return,res,mid,let,平方根,left 来源: https://blog.csdn.net/qq_56392992/article/details/121622574