leetcode-441-easy

Arranging Coins

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.

Example 1:


Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.
Example 2:


Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.
Constraints:

1 <= n <= 231 - 1

思路一:用求和公式循环计算。看了一下题解,最简单的是用一元二次方程直接计算答案。还有一种是二分法,搜索 1-n 中符合答案的解

    public int arrangeCoins(int n) {
        int result = 1;
        while (countSum(result) <= n) {
            result++;
        }

        return result - 1;
    }

    public static long countSum(long n) {
        return (1 + n) * n / 2;
    }
posted @ 2023-01-03 21:34  iyiluo  阅读(17)  评论(0)    收藏  举报