You have a total of n coinsthat you want to form in a staircase shape, where every k-throw must have exactly k coins.
Given n, findthe total number of full staircaserows that can be formed.
n is a non-negative integer andfits 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,就能得到可以填满几层,在使用这个方法的时候要注意,数据的范围可能会超出int,要使用long long ,还需要注意,当n刚好可以填满几层的时候这种情况需要注意一下
class Solution {
public:
int arrangeCoins(int n) {
long long collect = 0;
int u = 1;
while (collect <= n)
{
collect += u;
u++;
}
return u - 2;
}
};