题解 | #汽水瓶#

汽水瓶

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int a = in.nextInt();
            if (a>0) {
                System.out.println(count(a));
            }
        }
    }

    private static int count(int allBottle) {
        if (allBottle == 1) {
            return 0;
        } else if (allBottle == 2) {
            return 1;
        } else {
            int newBottle = allBottle / 3;
            int leftBottle = newBottle + allBottle % 3;
            return newBottle + count(leftBottle);
        }
    }
}

解题思路:

1, 已知有1~2个空瓶时能喝到的饮料数目, 整体问题可以不断分解到空瓶在3个以下情况;

2, 使用递归思想进行求解即可

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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