本文主要是介绍Java面试题:有20块钱,1块钱能买一瓶汽水,2个瓶子能换一瓶汽水,3个瓶盖能换一瓶汽水, 问一共能喝多少瓶汽水。(递归),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class BuySoda {public static void main(String[] args) {BuySoda buy = new BuySoda();int num = buy.buywater(20, 0, 0);System.out.println("一共能喝" + num + "瓶汽水");}/** 创建没水的方法,传入三个参数,分别是钱,瓶盖,瓶子*/public int buywater(int drinks, int bottle, int cap) { //递归方法,从(20,0,0)开始bottle = drinks + bottle;cap = drinks + cap;if(cap / 3 + bottle / 2 == 0) {//cap/3=能换多少瓶drinks,bottle / 2=能换多少瓶drinksreturn drinks;}return buywater(cap / 3 + bottle / 2, bottle%2, cap%3) + drinks ;//bottle % 2=剩下来几个空瓶,cap % 3=剩下来几个空瓶//buywater(cap / 3 + bottle / 2, bottle%2, cap%3):空瓶和空瓶盖能换多少瓶水:再加上上一次递归获得的水的数量}
}
进阶:瓶盖递归 (能借or不能借)
这篇关于Java面试题:有20块钱,1块钱能买一瓶汽水,2个瓶子能换一瓶汽水,3个瓶盖能换一瓶汽水, 问一共能喝多少瓶汽水。(递归)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!