441. Arranging Coins

来源:互联网 发布:做淘宝客服需要交钱吗 编辑:程序博客网 时间:2024/06/05 05:57

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 = 5The coins can form the following rows:¤¤ ¤¤ ¤Because the 3rd row is incomplete, we return 2.

Example 2:

n = 8The coins can form the following rows:¤¤ ¤¤ ¤ ¤¤ ¤Because the 4th row is incomplete, we return 3.

题目大意:给定一个数字n,按照第k行放k个硬币的方法,硬币能摆成几行

现在假设能摆成k行,现在求不等式k*(k+1)/2<=n,如果是等号的话,k=Math.sqrt(2*n+1/4)-1/2,因为k是整数,令k=(int)Math.sqrt(2*n),所以若不等式成立,

则返回k,若不成立,即k*(k+1)/2>n,则返回结果为k-1,代码如下:

        long l = n;        long k= (int) (Math.sqrt(2*l));        if(k*(k+1)/2<=l){        return (int) k;        }        else return (int) (k-1);