441. Arranging Coins

来源:互联网 发布:三浦翔平人不好知乎 编辑:程序博客网 时间:2024/05/22 12:45

题目:

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 = 5The coins can form the following rows:¤¤ ¤¤ ¤Because the 3rd row is incomplete, we return 2.

Example 2:

n = 8The coins can form the following rows:¤¤ ¤¤ ¤ ¤¤ ¤Because the 4th row is incomplete, we return 3.
思路:

本题塔型数据求和问题,思路比较简单,单独是先一个求和函数,利用递归实现,为了防止数据溢出

代码:

class Solution {public:    int arrangeCoins(int n) {        long num = n;        for(int i = sqrt(2*num);i>=0;i--)        {            if(sum(i)<=num)                return i;        }        return 0;    }private:    int sum(int n){        if(n==0)            return 0;        return sum(n-1)+n;            }};


原创粉丝点击