饮料换购-蓝桥杯

饮料换购


乐羊羊饮料厂正在举办一次促销优惠活动。乐羊羊C型饮料,凭3个瓶盖可以再换一瓶C型饮料,并且可以一直循环下去,但不允许赊账。


请你计算一下,如果小明不浪费瓶盖,尽量地参加活动,那么,对于他初始买入的n瓶饮料,最后他一共能得到多少瓶饮料。


输入:一个整数n,表示开始购买的饮料数量(0<n<10000)
输出:一个整数,表示实际得到的饮料数


例如:
用户输入:
100
程序应该输出:
149


用户输入:
101
程序应该输出:

151

程序源码: 


import java.util.Scanner;




public class DrinkBuyIn {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int totalBottom = totalBottom(n);
int totalBottom2 = totalBottom(n);
System.out.println("方法一求解结果:totalBottom = " + totalBottom);
System.out.println("方法二求解结果:totalBottom = " + totalBottom2);
}
/**
* 
* @param n 买的饮料的瓶数
* @return 总共能得到多少瓶
*/
public static int totalBottom(int n){
int bottom = n;
//瓶盖个数
int cap = n;
//瓶盖换取的新瓶
int newBottom = 0;
while(cap >= 3){
newBottom = (cap - cap%3) / 3;
bottom += newBottom;
cap = cap % 3 + newBottom;
}
return bottom;
}
/**
* 用递归实现
* @param n
* @return
*/
public static int totalBottom2(int n){
// 如果饮料瓶子的个数 小于 3, 则只能卖多少瓶是多少平, 瓶盖不足以换饮料瓶
if(n>= 1 && n < 3){
return n;
}
else{
return n + (n-n%3)/3 + totalBottom2((n-n%3)/3); //(n-n%3)/3 表示每次用瓶盖换取的饮料瓶的个数
}
}
}

程序结果:


















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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值