腾讯一次远程面试题:喝酒问题
题目:2元一瓶酒,4个瓶盖换1瓶酒,2个空瓶换1瓶酒,请问10元可以喝几瓶酒?
循环退出条件为,买不起酒或换不了酒
每次循环,计算这次循环能够换到的酒的数目和更新空瓶、瓶盖数
比如:
第一轮,买5瓶,剩余5空瓶,5盖;
第二轮,换3瓶,剩余4空瓶,4盖;
第三轮,换3瓶,剩余3空瓶,3盖;
第四轮,换1瓶,剩余2空瓶,4盖;
第五轮,换2瓶,剩余2空瓶,2盖;
第六轮,换1瓶,剩余1空瓶,3盖
非递归解法:
def drink_beer(money):
count = 0
beer,bottle,cap = 0,0,0
while money >= 2 or bottle >= 2 or cap >= 4:
beer += money // 2 + bottle // 2 + cap // 4
money %= 2
bottle = bottle % 2 + beer
cap = cap % 4 + beer
print("beer:{0}, bottle:{1}, cap:{2}".format(beer,bottle,cap))
count += beer
beer = 0
return count
print(drink_beer(10))
结果:
beer:5, bottle:5, cap:5
beer:3, bottle:4, cap:4
beer:3, bottle:3, cap:3
beer:1, bottle:2, cap:4
beer:2, bottle:2, cap:2
beer:1, bottle:1, cap:3
15