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.



首先明确第l行需要的星星数是 l(l+1)/2
l(l+1)/2 <= n
我一上来傻傻的 从0开始遍历,看何时不满足上述式子,自然是TLE了。

需要用开平方来求。

public class Solution {
    public int arrangeCoins(int n) {
        //res*(res+1)/2 <= n
        // res*res + res + 1/4 = 2n + 1/4
        // res + 1/2 = Math.sqrt(2n + 1/4)
        // res = Math.sqrt(2n+1/4)-1/2;
        
        return (int)(Math.sqrt(2*(long)n + 0.25) - 0.5);
    }
}

 写码的时候弱智一样,(int)(Math.sqrt(2*(long)n + 1/4) - 1/2); 发现答案不对,看了半天反应过来分数1/4 1/2的结果是0啊啊啊啊啊啊啊。。。

posted @ 2016-11-04 04:17  哇呀呀..生气啦~  阅读(514)  评论(0)    收藏  举报