美文网首页LeetCode By Go
[LeetCode By Go 97]441. Arrangin

[LeetCode By Go 97]441. Arrangin

作者: miltonsun | 来源:发表于2017-09-06 19:54 被阅读105次

题目

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
}

相关文章

网友评论

    本文标题:[LeetCode By Go 97]441. Arrangin

    本文链接:https://www.haomeiwen.com/subject/jbbvjxtx.html