[Leetcode学习-java]Arranging Coins(等差硬币排列)

问题:

难度:easy

说明:

给一个硬币数,然后摆在楼梯上,第n个楼梯有n个硬币,程序方面主要是推荐使用Math,因为java的c源码使用了IEEE745标准算法。

问题链接:https://leetcode.com/problems/arranging-coins/

输入案例:

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

我的代码:

水题,可以看到每一阶都多1,那么加起来就是一个等差数列,就可以用等差求数列和公式。

1、对于等差1,开始元素1的数列相加有:\sum_{1}^{n} x = \frac{n(n+1)}{2}

2、然后设\sum_{1}^{n}x = y得:y=\frac{n(n+1)}{2}

3、变为一元二次方程:\dpi{100} n^{2}+n-2y=0

4、根据求根公式得:n=\frac{-1+\sqrt{1+4*2y}}{2}

class Solution {
    public int arrangeCoins(int n) {
        // 解一元二次方程,要注意n转long,因为n是int范围数,8*n会超出int范围
        // 推荐使用sqrt,因为c源码里面是写了ieee754的标准算术源码
        return (int)Math.sqrt(1 + 8 * (long)n)- 1  >> 1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/107077470