首页 > 学院 > 开发设计 > 正文

LeetCode -- Arranging Coins

2019-11-08 02:10:57
字体:
来源:转载
供稿:网友
题目描述: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.其实就是求小于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;    }
上一篇:文章标题

下一篇:LeetCode 63. Unique Paths II

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表