441. The arrangement coins
You have a total of n coins, you need to put them into the shape of a ladder, the k-th row must have exactly k coins.
Given a number n, to find the full number of rows can be formed in a stepped line.
n is a nonnegative integer, and in the range of 32-bit signed integer in.
Example 1:
n = 5
Coins can be arranged in the following lines:
¤
¤ ¤
¤ ¤
Because the third row is not complete, so the return 2.
Example 2:
n = 8
Coins can be arranged in the following lines:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the fourth row is not complete, it returns 3.
PS:
According to the mathematical formula, k (k + 1) / 2 = n, which can be interpreted as a positive number: k = sqrt (2n + 1 /4) - 1/2. Then ask the whole can.
The only problem is that, where 2n + 1/4 may exceed sqrt function parameters.
Thus, what we can transform, k = sqrt (2) * sqrt (n + 1/8) - 1/2, so that it will not overrun the square root.
So, we have such a line of code
class Solution {
public int arrangeCoins(int n) {
return (int) (-1 + Math.sqrt(1 + 8 * (long) n)) / 2;
}
}