[LeetCode By Go 97]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.

解题思路

台阶的个数是从1到n的,很容易想到1+2+3+...+n = n(n+1)/2,所以比较
i * (i+1)/2 <= n && n < (i+1)
(i+2)/2,满足条件的i就是所求的rows

代码

func arrangeCoins(n int) int {
    if 0 == n {
        return 0
    }
    
    var ret int
    for i := 0; i <= n; i++ {
        if i * (i+1)/2 <= n && n < (i+1)*(i+2)/2 {
            ret = i
            break
        }
    }
    
    return ret
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容