题目原型:
Implement int sqrt(int x)
.
Compute and return the square root of x.
思想:
采用二分法逐渐逼近。
这里面是采用结果取最大整数法,如 sqrt(3)=1.717,但这个函数是返回1。然后是当x在(0,1]范围内时,返回1;当x为0时,返回0。
public class Sqrt
{
public int getResult(int x , double low , double high , double target)
{
if(x==0)
return 0;
if(x<=1&&x>0)
return 1;
if(low==high)
return (int)low;
double mid = (low+high)/2;
if(Math.abs(mid*mid-x)<=target)
return (int)mid;
else if((mid*mid-x)>target)
{
high = mid;
return getResult(x, low, high, target);
}
else
{
low = mid;
return getResult(x, low, high, target);
}
}
public int sqrt(int x)
{
int result = 0;
double target = 0.00001;
result = getResult(x, 0, x, target);
return result;
}
public static void main(String[] args)
{
Sqrt s = new Sqrt();
int x = 0;
System.out.println(s.sqrt(x));
}
}