/**
* 28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝?假如是50人,又需要买
多少瓶可乐?(需写出分析思路)
* 分析:解决问题需要进行分步进行。
* 1. 首先写出n瓶可以兑换出多少瓶
* 2. 再用循环求出1...n瓶中,刚好满足条件的个数。
*
* @author Barudisshu
*/
public class TestDrink {
public static void main(String[] args) {
int people = 28;
int change = 3;
int buys = count(people, change, 0);
int got = exchange(buys,change,0);
System.out.println(people + "人需要买" + buys+"瓶,并且可以兑换"+got+"瓶");
}
/**
* 可以兑换的个数
*/
public static int exchange(int bots, int con, int count) {
if (bots < con) { // 如果小于置换条件
count = 0;
} else if (bots == con) { // 刚好等于置换条件
count = 1;
} else { // 大于置换条件
if ((bots / con + bots % con) >= con) { // 可以再次置换
count = bots / con + exchange(bots / con + bots % con, con, count);
} else // 不可以再次置换
count = bots / con;
}
return count;
}
/**
* 获得实际个数
*/
public static int count(int people, int con, int count) {
int i = 0;
while (true) {
int total = i + exchange(i, con, count);
if (total >= people)
break;
i++;
}
return i;
}
}