【Leetcode441--数学】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.

题目大意:

用金币累一个楼梯,形式如下:

1

23

456

78910

就是说第n行有n个硬币,以此类推。问你最多能累多少层,多余出来且不足的不算,例如5的话返回2,8的话返回3。

 

分析:

这题很明显是一道数学题,我们首先观察规律

1

2 3

4 5 6

7 8 9 10

我们首先观察每一层的首项:

1 2 4 7

显然地,这是一个数列,并且首项间的关系为

 

 

 

所以,上下数列形式为:

 

上下累加得:

所以 :

 

 

所以我们就知道了每一层的首项的大小。

所以每一行的尾项为 An + n-1,得:

 

 

 

这时候,我们就可以根据n求出n行的首项(An0)和尾项(Ann)。

我们知道给出一个x,它一定是落在An0和Ann之间的。假设刚好落在(Ann)的时候。得出方程

 

 

 

 

 

根据求根公式:

 

 

即可求出n

(注意,此时的n是刚好落在Ann的时候,我们需要对结果向下取整)

 

JAVA CODE:

public class Solution {

    public int arrangeCoins(int n) {
        if (n == 0) {
            return 0;
        }
        long delta = (8L * n) + 1;
        int x = (int) (-1.0 + Math.sqrt(delta)) >> 1;
        return (int) x;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.arrangeCoins(8));
    }

}

 

posted @ 2017-04-14 15:45  hudiwei-hdw  阅读(218)  评论(0编辑  收藏  举报