LeetCode 441 Arranging Coins

xiaoxiao2021-02-28  19

题目:

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. 题目链接

题意:

给n个硬币,要求按要求排成多行,第k行需要k个硬币,返回可以按要求排成行的行数。

组成1行,需要1个

组成2行,需要1+2个

组成3行,需要1+2+3个

组成4行,需要1+2+3+4个

组成5行,需要1+2+3+4+5个。。。。。。。可推出公式

组成n行,需要(1+n)*n/2个

题目要求给出硬币,求出共有多少完整的行,就是对所推的公式求解,直接返回即可。

代码如下:

class Solution { public: int arrangeCoins(long long n) { return (sqrt(8*n + 1) - 1) / 2; } };

转载请注明原文地址: https://www.6miu.com/read-250354.html

最新回复(0)