题目:给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
注意:这里要用long,因为可能会溢出。
1:二分法:
class Solution {
public int mySqrt(int x) {
int left=0;
int right=x;
int s=0;
while(left<=right){
int mid=left+(right-left)/2;
if((long)mid*mid<=x){
s=mid;
left=mid+1;
}else{
right=mid-1;
}
}return s;
}
}
2:数学变换
x的1/2次方,写成e的1/2lnX次方。
class Solution {
public int mySqrt(int x) {
if(x==0)return 0;
int s=(int)Math.exp(0.5*Math.log(x));
return (long)(s+1)*(s+1)<=x?s+1:s;//因为是强制转为整型了,需要判断一下。
}
}
3:暴力求解:
class Solution {
public int mySqrt(int x) {
long s=0;
for(long i=0;(long)i*i<=x;i++){
s=i;
}return (int)s;
}
}