/**
* 28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝?假如是50人,又需要买多少瓶可乐?
(需写出分析思路)
* 分析:解决问题需要进行分步进行。
* 1. 首先写出n瓶可以兑换出多少瓶
* 2. 再用循环求出1...n瓶中,刚好满足条件的个数。
* (不考虑向店主借一瓶,筹够三瓶后还一瓶的情况,虽然这里也可以实现,但是假如店主不肯怎么办?
假如没货了呢?-_-!据说小学生喜欢转牛角尖)
* @author Barudisshu
*/
public class TestDrink {
public static void main(String[] args) {
System.out.println(count(28, 3, 0));
}
/**
* 可以兑换的个数
*/
public static int exchange(int bots, int con, int count) {
if (bots < con) { // 如果小于置换条件
count += bots;
} 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 bots, int con, int count) {
int total;
int i = con;
while (true) {
total = i + exchange(i, con, count);
if (total >= bots)
break;
i++;
}
return i;
}
}
原文:http://my.oschina.net/Barudisshu/blog/420114