LeetCode-441. Arranging Coins

来源:互联网 发布:漫画快速制作软件 编辑:程序博客网 时间:2024/05/17 07:01

问题: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;    }};
0 0
原创粉丝点击