题目:
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.
可能是这道题真的很简单,第一次这么快写出来了。我的思路写个循环就是和不断递减,要注意题目说的是非负,然后要写0的情况。
public int arrangeCoins(int n) {
int i=0;
for(;i<n;i++){
n= n-i;
if(n<=i) break;
}
return i;
}
然后网上看了一下大神的解法,瞬间就被秒杀了。。。。
已知等差数列的和Sn,首项a1=1,d=1,求n
/* 推导过程:
* 等差数列求和:第一项为1,公差为1
* 公式S = (x + 1)x / 2,x表示阶数
* S <= n
* (x + 1)x / 2 <= n
* x^2 + x = 2n
* (x + 1/2)^2 = 2n + 1/4
* (2x + 1)^2 = 8n + 1
* 2x + 1 = sqrt(8n + 1)
* x <= {sqrt(8n + 1) - 1} / 2
* 最后结果取整
*/
public int arrangeCoins(int n) {
return (int)((Math.sqrt(8*(long)n + 1) - 1)/2);
}