LeetCode -- Arranging Coins

来源:互联网 发布:苹果手机频谱软件 编辑:程序博客网 时间:2024/06/08 19:43
题目描述:


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 = 5


The coins can form the following rows:
¤
¤ ¤
¤ ¤


Because the 3rd row is incomplete, we return 2.


其实就是求小于N的最大M,M为1+...+K。
思路:
遍历1到n/2即可。


实现代码:


public int ArrangeCoins(int n) {        if(n == 0){            return 0;        }        if(n == 1){            return 1;        }                        var half = n/2 + 1;                var sum = 0;var count = 0;        for(var i = 1;sum >= 0 && i <= half && sum < n; i++){            sum += i;count ++;        }        if(sum > n || sum < 0){count --;}//Console.WriteLine(sum);        return count;    }


1 0
原创粉丝点击