Description:
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.
题意:给定一个数量的硬币,要找第k行放置k个,求最多可以放置几行(只有当一行放置足够数量的硬币,这一行才计入结果);
解法:我们假设一共放置了n行,给定的硬币数为num,我们可以得到:
1
+
2
+
3
+
4
+
.
.
.
.
.
.
+
n
=
(
1
+
n
)
∗
n
2
<
=
n
u
m
1 + 2 + 3 + 4 + ......+ n = \frac{(1+n)*n}{2}<= num
1+2+3+4+......+n=2(1+n)∗n<=num
因此,我们现在就是要找到令不等式成立的最大的那个n;
Java
class Solution {
public int arrangeCoins(int n) {
long result = 0;
while ((1 + result) * result / 2 <= n) result++;
return (int)(result-1);
}
}