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:

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.

可看作等差数列求和

假设完成K层,一共n个,由等差数列求和公式有: 
(1+k)*k/2 = n 
一步步推导: 
k+k*k = 2*n 
k*k + k + 0.25 = 2*n + 0.25 
(k + 0.5) ^ 2 = 2*n +0.25 
k + 0.5 = sqrt(2*n + 0.25) 
k = sqrt(2*n + 0.25) - 0.5 
这里k是个浮点数,将其取为小于k的最大整数就可以 
class Solution {
public :
    int arrangeCoins(int n) {
        return (int) (sqrt(2*(long)n+0.25) - 0.5);
    }
}

猜你喜欢

转载自blog.csdn.net/chineseqsc/article/details/79678539