1.求1 + 2 + 3 + ... + 100 的结果
public class TestCacu { public static int add(int first, int last, int result) { result += last; if (last == first) { return result; } else { return add(first, last - 1, result); } } public static void main(String[] args) { int res = add(0, 100, 0); System.out.println(res); } }
2:一个人买汽水,一块钱一瓶汽水,三个瓶盖可以换一瓶汽水,2个空瓶可以换一瓶汽水,问20块钱总共可以买多少瓶汽水,写程序算出来
public class TestBuyWater { public static int returnBuy(int waterNum, int coverNum, int bottleNum) { int newWater = coverNum / 3 + bottleNum / 2; waterNum += newWater; coverNum = coverNum % 3 + newWater; bottleNum = bottleNum % 2 + newWater; if (coverNum < 3 && bottleNum < 2) { return waterNum; } else { return returnBuy(waterNum, coverNum, bottleNum); } } public static void main(String[] args) { int res = returnBuy(20,20,20); System.out.println(res); } }
今天的一些练手题,涉及到了一点递归的思想。记录一下