Arranging Coins
Problem
You have n
coins and you want to build a staircase with these coins. The staircase consists of k
rows where the ith
row has exactly i
coins. The last row of the staircase may be incomplete.
Given the integer n
, return the number of complete rows of the staircase you will build.
Constraints
1 <= n <= 231 - 1
Solution
The problem Arranging Coins
can be solved using a simple equation. Sum of all integers between [1, n]
is n * (n + 1) / 2
. Therefore, the result can be calculated by finding the largest integer x
where x * (x + 1) / 2 <= n
. Based on Quadratic formula, x
can be gained using the following equation.
Implementation
class Solution
{
public:
int arrangeCoins(int n) { return (sqrt(1 + 8.0 * n) - 1) / 2; }
};