0%

Javascript 瓶盖换啤酒问题

题目是这样的,啤酒2块钱一瓶,2个空瓶子或者4个瓶盖可以换一瓶新的,如果手上有10元钱,可以喝多少瓶啤酒。写了个 JS 脚本来计算,代码如下(demo):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var changing = function(money, price){
var count = parseInt(money/price),
bottle = count,
lid = count,
lidRate = 4,
bottleRate = 2;
(function change(){
// 兑换盖子
if(lid >= lidRate){
var lGet = parseInt(lid/lidRate);
count += lGet;
bottle += lGet;
lid -= lGet*(lidRate-1);
console.log('使用瓶盖'+ lGet*lidRate +'个,兑换:'+ lGet +'瓶');
console.log('已喝:'+ count + ', 剩余瓶盖:'+ lid +', 剩余空瓶:'+ bottle);
}
// 兑换空瓶
if(bottle >= bottleRate){
var bGet = parseInt(bottle/bottleRate);
count += bGet;
bottle -= bGet;
lid += bGet*(bottleRate-1);
console.log('使用空瓶'+ bGet*bottleRate +'个,兑换:'+ bGet +'瓶');
console.log('已喝:'+ count + ', 剩余瓶盖:'+ lid +', 剩余空瓶:'+ bottle);
}
// 判断剩余
if(bottle >= bottleRate || lid >= lidRate){
change();
} else {
console.log('总共喝:'+ count + ', 剩余瓶盖:'+ lid +', 剩余空瓶:'+ bottle);
}
})();
};
// 开始计算
changing(10, 2);

BTW:题目的答案是最终可以喝 15 瓶(计算过程如下图),你答对了吗?

欢迎关注我的其它发布渠道