# LeetCode C++ 441. Arranging Coins【Math/Binary Search】简单

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.


### 解法1 迭代

class Solution {
public:
int arrangeCoins(int n) {
if (n <= 1) return n; //n=0->0, n=1->1
int level = 0;
for (int i = 1; n - i >= 0; ++i) {
++level;
n -= i;
}
return level;
}
};


执行用时：16 ms, 在所有 C++ 提交中击败了19.02% 的用户



class Solution {
public:
int arrangeCoins(int n) {
int level = 1;
while (n >= level) {
n -= level;
++level;
}
return level - 1;
}
};


### 解法2 二分

class Solution {
public:
int arrangeCoins(int n) {
if (n <= 1) return n; //特判,注意:n=1不存在第一个满足mid*(mid+1)>2n的mid
uint64_t lo = 0, hi = n, mid, n2 = 2ull * n; //找到最后一个满足mid*(mid+1)<=2n的mid
while (lo < hi) { //找到第一个满足mid*(mid+1)>2n的mid
mid = lo + (hi - lo) / 2;
if ((mid + 1) * mid > n2) hi = mid;
else lo = mid + 1;
}
return lo - 1;
}
};


执行用时：4 ms, 在所有 C++ 提交中击败了81.62% 的用户



### 解法3 数学

class Solution {
public:
int arrangeCoins(int n) {
return (-1 + sqrt(1 + 8ll * n)) / 2;
}
};


执行用时：0 ms, 在所有 C++ 提交中击败了100.00% 的用户



10-30 335

06-05 9067
04-04 428
05-16 386
03-26 11
04-08 396
04-08 576
02-28 339
01-09 2253
07-05 533
10-17 1万+
09-27 1万+
11-22 9