10元買啤酒問題Java解法

zhuxiaoxi發表於2018-10-25

10元去買啤酒,2元一瓶。每兩個瓶可以換一瓶啤酒,每四個瓶蓋可以換一瓶啤酒。最多買幾瓶?

public class Java {
        public static void main(String[] args) {
                int money = 10;
                int beer = money/2;
                int cover = beer;
                int bottle = beer;
                int buy = beer;
                while(true){
                        if(cover >= 4){
                                cover -= 4;
                                buy = buy + 1;
                                cover += 1;
                                bottle += 1;
                        }
                        if(bottle >= 2){
                                bottle -= 2;
                                buy += 1;
                                cover += 1;
                                bottle += 1;
                        }
                        if(cover < 4 && bottle < 2){
                                break;
                        }

                }
                System.out.print("buy: " + buy);
        }
}

相關文章