【Leetcode】441. Arranging Coins

本文探讨了如何使用循环和数学公式解决硬币阶梯问题,即用n枚硬币形成一个阶梯形状,每行比上一行多一枚硬币,求最多能形成多少行完整的阶梯。通过分析,提供了一个简单的循环解决方案,并介绍了一种更高效的数学公式解法。

题目:

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);      
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值