LeetCode-441. Arranging Coins

本文探讨了LeetCode上的硬币楼梯问题,通过等差数列原理解析如何利用C++实现硬币排列,以形成完整的楼梯形状。每层楼梯需要比前一层多一个硬币,直到无法继续增加为止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:https://leetcode.com/problems/arranging-coins/?tab=Description
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.
你有n枚硬币,想要用来组成一个完整的楼梯,第m层有m个硬币。给出n,返回可以组成的完整楼梯的层数。n是一个非负数,且满足32位int的范围。
分析:等差数列排放的形式。对于第m层,排满的要求是剩下的硬币数量大于等于m。
C++代码:

class Solution {
public:
    int arrangeCoins(int n) {
        int num=0;
        int i=1;
        while(n>=i){
            num++;
            n=n-i;
            i=i+1;
        }
        return num;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值