当前位置: 代码迷 >> 综合 >> 441. Arranging Coins
  详细解决方案

441. Arranging Coins

热度:2   发布时间:2023-12-16 04:28:07.0

原题链接

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.

思路:显然等差数列求和,要解的方程为:

k?(k+1))2?n k ? ( k + 1 ) ) 2 ? n

解出k的范围为:

k??1+1+8n??????2 k ? ? 1 + 1 + 8 n 2

计算后边式子的值取整即可,注意8n可能会超过int范围,需要向上转换。

AC代码:

class Solution {
public:int arrangeCoins(int n) {return (int)((sqrt(1+8.0*n)-1)/2.0);}
};