Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
给你一个非负整数 x
,计算并返回 x
的 算术平方根 。由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
//手撕
class Solution {
public int mySqrt(int x) {
int left =0;
int right = x;
int ans=-1;
while(left<=right){
int mid = left + (right-left)/2;
if((long)mid*mid<=x){
ans=mid;
left=mid+1;
}else{
right=mid-1;
}
}
return ans;
}
}
点评:本题利用二分查找法解题,通过左指针逼近的方法解题
如何解题:首先编写二分查找的大致框架,通过循环不断判断mid平方与目标值的差距找到最小接近或等于目标值的mid值即是答案,难点在寻找边界条件和理解二分查找指针运行过程。