题解 | #汽水瓶#尽可能好理解的递归Java

汽水瓶

https://www.nowcoder.com/practice/fe298c55694f4ed39e256170ff2c205f

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
         bottle(in);
    }

    public static void bottle(Scanner in) {
        int n = 0;
        // List<Integer>list=new ArrayList<>();
        while (in.hasNextInt()) {
            n = in.nextInt();
            if(n==0){
                continue;
            }
            System.out.println(sum(n));
        }
    }
    
    public static int sum(int n) {//n就代表空瓶子
        if (n == 1) {
            return 0;
        }
        if (n == 2) {
            return 1;
        }
        int sum = n / 3;//1水
        //在借之前要把前面的空瓶子消耗完,借是最后一步。
        int l = n % 3;//1瓶 如果剩下2瓶,那么可以借一瓶,喝完后再还回去res+1
        int res = 0;
        boolean flag = false;
        if (l == 2) {
            res += 1;
            flag = true;//借据
        }
        int tota = sum + res;//这是总水数
        int totaBottle = flag?tota-1:tota+l;//这是总瓶数,如果有借据得减一个瓶子.tota+l是加上了前面余下的1
        return tota + sum(totaBottle);//最后递归调用时的参数就是兑换的水瓶子+剩余的空瓶子
    }
}

全部评论

相关推荐

程序员小白条:这简历除了学历确实没啥亮点,先找个中小厂再说吧
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务