441. Arranging Coins
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5
The coins can form the following rows:
¤
¤ ¤
¤ ¤
Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8
The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the 4th row is incomplete, we return 3.
分析:直接用公式一行代码就能解决
class Solution {
public:
int arrangeCoins(int n) {
return (int)((sqrt(8 * (long)n + 1) - 1)/ 2);
}
};
本文介绍了一种通过数学公式快速解决硬币排列问题的方法。给定一定数量的硬币,目标是将这些硬币排列成阶梯形状,每层比上一层多一个硬币。文章提供了一个简洁的C++实现方案,利用数学公式计算可以完整构成的最大阶梯层数。
320

被折叠的 条评论
为什么被折叠?



