LeetCode By Go

[LeetCode By Go 97]441. Arrangin

2017-09-06  本文已影响105人  miltonsun

题目

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
}
上一篇下一篇

猜你喜欢

热点阅读