最近面试碰到一个喝汽水的问题,记录一下
原始问题:20块钱,一块钱一瓶汽水,两个空瓶能换一瓶汽水,问最终能喝多少瓶汽水?
自我扩展:m元钱, 一瓶汽水单价是n, y个空瓶换一瓶汽水,问最终能喝多少瓶汽水?
在VC6上面测试大致通过,
//递归解法
#include<stdio.h>
/*
* Function:空瓶换汽水
* 输入 emptyNum:空瓶数
* BottleChange:换到一瓶汽水所需的空瓶数
* 返回 换到的汽水数
*/
int emptyToSoda(int emptyNum, int BottleChange)//emptyNum:
{
if(emptyNum < BottleChange)//空瓶不足以换到一瓶汽水了
return 0;
return 1+ emptyToSoda(emptyNum-BottleChange+1, BottleChange);//换到一瓶汽水(+1),把所换汽水的瓶子计入下一轮
}
/*
* Function:计算喝到的汽水
* 备注 m元钱, 一瓶汽水单价是n, y个空瓶换一瓶汽水,问最终能喝多少瓶汽水?
* 输入 money:初始用于购买汽水的金额
* singlePrice:一瓶汽水的单价
* BottleChange:换到一瓶汽水所需的空瓶数
* 返回 喝到的汽水数
*/
int calcSoda(int money, int singlePrice, int BottleChange)
{
int initBottle = money/ singlePrice;
return initBottle+emptyToSoda(initBottle, BottleChange);//钱购买的汽水和空瓶换的汽水
}
int main()
{
int money =20;
printf("%d 块钱能喝多少瓶水:%d \r\n",money,calcSoda(20, 1, 2));
printf("%d 块钱能喝多少瓶水:%d \r\n",money,calcSoda(20, 1, 3));
return 0;
}
//迭代解法
。。