IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]LeetCode -- Arranging Coins

    csharp25发表于 2017-02-19 22:42:58
    love 0
    题目描述:


    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;
        }




沪ICP备19023445号-2号
友情链接