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.
题目大意:给定一个数字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);