啤酒1元1瓶,3个瓶盖换1瓶,2个空瓶子换1瓶,问10元钱可以喝几瓶

非递归算法

/**
 * 啤酒1元1瓶,3个瓶盖换1瓶,2个空瓶子换1瓶,问10元钱可以喝几瓶
 */
public class Test {

    public static int cunt(int n) {
        int cnt = n;
        int a = n, b = n, i;
        while (a >= 2 || b >= 3) {
            System.out.print(a + "-" + b);
            if (a >= 2) {
                i = a / 2;
                b += i;
                cnt += i;
                a = a % 2 + i;
            } else {
                i = b / 3;
                a += i;
                cnt += i;
                b = b % 3 + i;
            }
            System.out.println(" -> " + a + "-" + b + " tol:" + cnt);
        }
        return cnt;
    }

    public static void main(String[] args) {
        System.out.println(cunt(4));
    }
}

 

posted on 2019-09-27 10:53  疯狂的妞妞  阅读(403)  评论(0编辑  收藏  举报

导航