空瓶子换汽水问题

       用空瓶子换汽水经常遇到 今天在论坛上有人提出来,给的算法用递归实现的 如果数量在百万那么时间复杂度我认为不合理

      其实我认为这个问题很简单 如果几十个人需要喝汽水 完全可以根据数学模型口算出来 也就是说时间复杂度为n

      数学模型:

      N个瓶子换一瓶汽水。(假设瓶子的价钱为1)

     瓶子价钱x 一瓶汽水除去瓶子本身的价钱实际价钱为y那么

     N * x = x + y;

    y = (N - 1 ) * x;

   那么至少需要的money就很容易计算出来就可以计算出开始需要买几瓶汽水了

  java代码如下:

 

package cn.xy.csdn;

public class Bottletosoda {

	public static final int bottoleprice = 1;// 一个瓶子的价钱

	private int percount = 3;// 每瓶汽水需要几个空瓶子换

	private int sodacount = -1;// 需要的汽水的数量

	public int sodaprice = 2;
	
	public boolean flag = false;//是否允许使用最后的两个瓶子换一瓶汽水在将空瓶抵给卖方

	public int getPercount() {
		return percount;
	}

	public void setPercount(int percount) {
		this.percount = percount;
	}

	public int getSodacount() {
		return sodacount;
	}

	public void setSodacount(int sodacount) {
		this.sodacount = sodacount;
	}

	public void compsodaprice() {
		this.setSodaprice(bottoleprice * (this.getPercount() - 1));
	}

	public int getSodaprice() {
		return sodaprice;
	}

	public void setSodaprice(int sodaprice) {
		this.sodaprice = sodaprice;
	}

	public int buysodanumber() {

		compsodaprice();
		int needminmoney = this.getSodaprice() * this.getSodacount();
		int lucysocle = needminmoney % (this.getSodaprice() + bottoleprice);
		int minnumber =   needminmoney
				/ ((this.getSodaprice() + bottoleprice));
		float realnum = (float) needminmoney / (float) (this.getSodaprice() + bottoleprice);
		if ((!this.flag && lucysocle == 0) || realnum > (float)minnumber) {
			minnumber += 1;
		}
		return minnumber;
	}

	public static void main(String[] s) {
		Bottletosoda bt = new Bottletosoda();
		bt.setSodacount(27);
		System.out.println(bt.getSodacount() + "个人都喝到汽水至少应买的汽水瓶数为:"
				+ bt.buysodanumber());
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值