441. Arranging Coins
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:
|
|
Example 2:123456789n = 8The coins can form the following rows:¤¤ ¤¤ ¤ ¤¤ ¤Because the 4th row is incomplete, we return 3.
Binary Search
根据等差数列求和公式, 设步数为x, 那么 x * (x + 1) / 2 <= n
. 结果为满足不等式的最大的x. x的范围是[1, n], 可以用二分查找实现.
代码如下:
要处理溢出的情况
|
|
Math
求满足 $x^2 + x - 2 * n <= 0$ 的最大的x. 二元一次方程有两个解, 这里较大的解即为所求. $x = \frac{-b + \sqrt{b^2 - 4ac}}{2a}$
|
|