找到(n+1)*n/2 与所给硬币数最接近的n
(1)直接遍历寻找
public static int arrangeCoins(int n)
{
for(int i =1;;i++)
{
n-=i;
if(n<=i)
return i;
}
}
(2)二分法进行查找
public static int arrangeCoinsTwo(int n)
{
int low =1,high = n;
while(low<=high)
{
int mid = (low+high)/2;
if((1+mid)*mid/2==n)
return mid;
else if((1+mid)*mid/2<n)
low =mid+1;
else high = high-1;
}
return high;
}
(3)牛顿迭代
public static int arrangeCoinsThree(int x)
{
if(x==0)return 0;
return (int)getSqrt(x,x);
}
public static double getSqrt(int x,int n) {
double res = (x+(2*n-x)/x)/2;
if(res==x)
return x;
else
return getSqrt((int)res,n);
}