LeetCode——441.Arranging Coins

441.Arranging Coins

  • 问题描述

      您总共有n个硬币,您想要形成阶梯形状,其中每k行必须有正好k个硬币。给定n,找到可以形成的全部楼梯行的总数。

      n是非负整数,适合32位有符号整数的范围。

      例子:

n = 5

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

 

n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
  • 解法思路

      1.循环减n,每次减的数从一累加,直到n<0

      2.对于循环语句的选择,有for,while。两者都可以。对于有条件的截止循环的题目,

      while循环跟for循环然后在循环体内加上判断语句break循环可以划等号。

  • 代码
class Solution {
     public int arrangeCoins(int n) {
        int level = 0;
        while(n > level) {
            level++;
            n = n - level;
        }
        return level;
    }
}
class Solution {
     public int arrangeCoins(int n) {
        int i,t,temp= 0;
	    for(i=1;i<=n;i++){
            n=n-i;
            if(n==0){
                t=i;
                break;
            }
            else if(n<0){
                t=i-1;
                break;
            }
	    }
        return t;
    }
}

 

  • 总结

     1.对于有条件的截止循环的题目,我们大多数人的第一反应是用for循环,但对于循环截止条件不是i=n的情况时,

       可能while循环更加适合。总结一句是如果碰到需要循环的题目时,特别是有条件的结束循环,一定要考虑一

      下while实现的可能性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值