Implement int sqrt(int x)
.
Compute and return the square root of x.
Subscribe to see which companies asked this question
public class Solution {
public int mySqrt(int x) {//中间步骤要用long类型,不然会溢出
if(x<=0)return x;
long a = (long)x;
int i = 1;
while((long)i*i<a){
i=i<<1;
}
int tem = i;
int ret = 0;
for(;tem>0;tem=tem>>1){
if((long)(ret+tem)*(ret+tem)<=x)ret+=tem;
}
return ret;
}
}