描述
实现函数 int sqrt(int x).
计算并返回 x 的平方根(向下取整)
要求:空间复杂度 O(1),时间复杂度 O(logx)
题解:利用二分法求解,注意利用乘法对数进行验证,可能会导致数据溢出,而使用除法,则要注意除数不为0
public class Solution {
/**
*
* @param x int整型
* @return int整型
*/
public int sqrt (int x) {
// write code here
if(x==0) return 0;
if(x==1) return 1;
int high=x;
int low=0;
int mid=(high+low)/2;
while(true)
{
if(x/mid==mid) return mid;
if(x/mid>mid&&x/(mid+1)<(mid+1))
return mid;
if(x/mid>mid)
{
low=mid+1;
mid=(low+high)/2;
}
else
{
high=mid-1;
mid=(low+high)/2;
}
}
}
}