java練習題:換汽水問題

問題:某商店規定,三個空汽水瓶可以換一瓶汽水。小王手上有十個空汽水瓶,他最多可以換多少瓶汽水,答案是5瓶,方法如下:先用9個空瓶子換3瓶,喝掉這3瓶之後,剩4個空瓶子,再用3瓶去換一瓶,喝完剩2個空瓶子,這時可以向老闆借一瓶,喝掉這瓶滿的,剩3個空瓶,換一瓶滿的還給老闆,如果小王手裏有n個空瓶,問最多可以換多少瓶汽水喝?

import java.util.Scanner;
class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int s=0;
        int h=0;
        int count=0;
        if (n != 0 && n <= 100) {


            while (n >= 3) {
                h = n / 3;
                s = n % 3;
                n = s + h;

                count = count + h;


            }
        }


        if(n==2){
            count=count+1;
        }



        System.out.println(count);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章