題目描述:
有這樣一道智力題:“某商店規定:三個空汽水瓶可以換一瓶汽水。小張手上有十個空汽水瓶,她最多可以換多少瓶汽水喝?”答案是5瓶,方法如下:先用9個空瓶子換3瓶汽水,喝掉3瓶滿的,喝完以後4個空瓶子,用3個再換一瓶,喝掉這瓶滿的,這時候剩2個空瓶子。然後你讓老闆先借給你一瓶汽水,喝掉這瓶滿的,喝完以後用3個空瓶子換一瓶滿的還給老闆。如果小張手上有n個空汽水瓶,最多可以換多少瓶汽水喝?
輸入描述:
輸入文件最多包含10組測試數據,每個數據佔一行,僅包含一個正整數n(1<=n<=100),表示小張手上的空汽水瓶數。n=0表示輸入結束,你的程序不應當處理這一行。
輸出描述:
對於每組測試數據,輸出一行,表示最多可以喝的汽水瓶數。如果一瓶也喝不到,輸出0。
示例1:
輸入:
3
10
81
0
輸出:
1
5
40
代碼:
import java.util.*;
public class Main {
public static void main ( String[] args ) {
Scanner in = new Scanner( System.in );
while( in.hasNextLine()) {
int n = Integer.parseInt( in.nextLine() );
if ( n == 1 ) {
System.out.println( 0 );
break;
}
if ( n == 0 ) {
break;
}
int x = n / 3 + n % 3;
int sum = n / 3;
if ( x >= 3 ) {
do {
sum += x / 3;
x = x % 3 + x / 3;
} while( x >= 3 );
if ( x == 1 ) {
System.out.println( sum );
}
if ( x == 2 ) {
System.out.println( sum+1 );
}
}
else if ( x == 1 ) {
System.out.println( sum );
}
else {
System.out.println( sum+1 );
}
}
in.close();
}
}