JS 求平方根
实现函数 int sqrt(int x).
计算并返回x的平方根(向下取整)
用二分法
function sqrt( x ) {
// write code here
//二分查找
var left = 0;
var right = x;
var res = -1;
while(left<=right){
var mid = Math.floor(left+(right-left)/2);
if(mid*mid<=x){
res = mid;
left = mid+1;
}else{
right=mid-1;
}
}
return res;
}
module.exports = {
sqrt : sqrt
};