黑马程序员技术交流社区
标题:
入学测试题——购买可乐的2种解法
[打印本页]
作者:
java_dream
时间:
2014-10-20 02:09
标题:
入学测试题——购买可乐的2种解法
/**
* 10、 28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝?
* 假如是50人,又需要买多少瓶可乐?(需写出分析思路)
*
* @author live-dream
*
*/
public class Test10 {
public static void main(String[] args){
int people = 50;
// int total = buy1(people);
int total = buy2(people,1,0);
System.out.println(people+"个人,需买"+total+"瓶可乐");
}
/**一般解法:
*
* @param people
* @return
*/
public static int buy1(int people){
int buy = 0;//购买的数量
int total = 0;//购买的数量+用瓶盖换取的数量
int bCap = 0;//当前持有的瓶盖数量
while(total<people){
buy++;//购买一瓶
total++;//总数增加1
bCap++;//得到一个瓶盖
if(bCap==3){//如果瓶盖够3个
total++;//换取一瓶,总数增加1
bCap=1;//持有一个瓶盖
}
}
return buy;
}
/**递归解法:
*
* @param people 需要的可乐数量
* @param buy 购买的可乐数量
* @param give 赠送的可乐数量
* @return 返回购买的数量buy
*/
public static int buy2(int people,int buy,int give){
give = (buy+give)%3==0 ? give+1 : give; //如果 购买的数量buy+赠送的数量give刚好够3瓶,又可获赠一瓶
if((buy+give)<people){ //如果购买的数量+赠送的数量还不够,再买
return buy2(people,++buy,give);
}else{ //如果数量够了,就返回该买的数量
return buy;
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2