常见面试题:N个人买可乐,买5瓶送一瓶,至少要买几瓶可乐够喝?
递归解决:
参数说明:
people : 总共人数也就是N
real:当前几个瓶子可以兑换
buy:掏钱钱买的瓶数
sum:总共几个瓶子
package site.iknown.farm.test;
public class Main
{
private static int divide(int people, int empty, int buy, int sum)
{
if(empty != 5)
{
//空的瓶子不够,需要买新的
buy++;
empty++;
}
else
{
//换了一个瓶子,还剩一个瓶子
empty = 1;
}
sum ++;
return people == sum ? buy : divide(people, empty, buy, sum);
}
public static void main(String[] args)
{
for(int i=1;i<=1024;i++)
{
System.out.println(i+"人需要买"+divide(i, 0, 0, 0)+"瓶可乐");
}
}
}