经典智力题:汽水瓶的数量

题目描述

有这样一道智力题:“某商店规定:三个空汽水瓶可以换一瓶汽水。小张手上有十个空汽水瓶,她最多可以换多少瓶汽水喝?”答案是5瓶,方法如下:先用9个空瓶子换3瓶汽水,喝掉3瓶满的,喝完以后4个空瓶子,用3个再换一瓶,喝掉这瓶满的,这时候剩2个空瓶子。然后你让老板先借给你一瓶汽水,喝掉这瓶满的,喝完以后用3个空瓶子换一瓶满的还给老板。如果小张手上有n个空汽水瓶,最多可以换多少瓶汽水喝?

输入描述:

输入文件最多包含10组测试数据,每个数据占一行,仅包含一个正整数n(1<=n<=100),表示小张手上的空汽水瓶数。n=0表示输入结束,你的程序不应当处理这一行。

输出描述:

对于每组测试数据,输出一行,表示最多可以喝的汽水瓶数。如果一瓶也喝不到,输出0。

输入例子:

3
10
81
0

输出例子:

1
5
40

首先介绍最牛逼的算法。。。。。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int beginNumOfSoda = sc.nextInt();
            // 输入0时结束循环
            if (beginNumOfSoda == 0) {
                break;
            }
            // 通过数学分析发现就是n/2瓶
            System.out.println(beginNumOfSoda / 2);
        }
    }
}

接下来就是模拟了

我的模拟:

import java.util.Scanner;

/**
 * Created by user on 2017/5/12. 模拟小明的汽水瓶的算法
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int beginNumOfSoda = sc.nextInt(); // 输入数据被控制在0~100
            if (beginNumOfSoda == 0) {
                break;
            }
            int sumOfEnd = 0;
            int t = beginNumOfSoda;
            // 模拟循环题意过程,先把多余的算出来,再把3的倍数算出来,再让结果增加
            // 改变剩余的瓶子t;
            while (t >= 3) {
                int a = t % 3; // a表示刚开始的数量,;
                int b = t / 3; // b表示可以新获得的瓶子
                sumOfEnd += b;
                t = a + b;
            }
            if (t >= 2) {
                sumOfEnd++;
            }
            System.out.println(sumOfEnd);
        }
    }
}

另一种模拟:

import java.util.Scanner;

public class Main {
    public int result(int n) {
        int result = 0;
        int total = n;
        while (total > 0) {// 不断循环
            if (total == 2) {// 只剩下两瓶就+1
                total++;
            }
            total = total - 3;
            if (total >= 0) {// 每减三瓶总数加一瓶,结果也加一
                total++;
                result++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Main main = new Main();
        while (sc.hasNext()) {
            int num = sc.nextInt();
            if (num == 0)
                break;
            System.out.println(main.result(num));
        }
    }
}

 

 

posted @ 2017-05-16 00:10  过道  阅读(304)  评论(0编辑  收藏  举报