问题:
难度: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的数列相加有:
2、然后设得:
3、变为一元二次方程:
4、根据求根公式得:
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;
}
}