1-Algorithm problem: empty bottle for water

/ **
* There is a puzzle: "A store stipulates: three empty soda bottles can be exchanged for a bottle of soda. Xiao Zhang has ten empty soda bottles in
her hand. * How many bottles of soda can she drink at most?" The answer is 5 bottles,
* The method is as follows:
* First replace 9 empty bottles for 3 bottles of soda, drink 3 full bottles, after drinking 4 empty bottles, use 3 again for another bottle, drink this full bottle, this There are 2 empty bottles left.
* Then you let the boss first lend you a bottle of soda, drink the full bottle, and use 3 empty bottles to replace the full bottle with the boss. If Xiao Zhang has n empty soda bottles in his hand, how many bottles can he change?
* /

1  / ** 
2  * There is a puzzle: "A store stipulates: three empty soda bottles can be exchanged for a bottle of soda. Xiao Zhang has ten empty soda bottles in her hand.
 3  * How many bottles of soda can she drink at most? "The answer is 5 bottles,
 4  * The method is as follows:
 5  * First replace 9 empty bottles for 3 bottles of soda, drink 3 full bottles, after drinking 4 empty bottles, use 3 for another bottle, drink this When the bottle is full, there are 2 empty bottles left.
6  * Then you let the boss first lend you a bottle of soda, drink the full bottle, and use 3 empty bottles to replace the full bottle with the boss after drinking. If Xiao Zhang has n empty soda bottles in his hand, how many bottles can he change?
7  * / import java.io.IOException;
 8  
9  import java.util.Scanner;
 10  
11  public  class Main {
 12      public  static  void main (String [] args) throws IOException {
 13          Scanner sc = new  Scanner(System.in);
14         while(sc.hasNext()){
15             int n = sc.nextInt();
16             if(n>=1 && n<=100){
17                 System.out.println(getNum(n));
18             }else{
19                 break;
20             }
21         }
22     }
23 
24   //递归求解
25     public static int getNum(int n) {
26         if(n<1 && n>100){
27             return-1 ;
 28          }
 29          if (n == 1 ) {
 30              return 0 ;
 31          }
 32       // If there are two empty bottles, you can change a bottle of water 
33          if (n == 2 ) {
 34              return 1 ;
 35          }
 36       // What n / 3 gets is how many bottles of water can be directly exchanged for the n empty bottles
 37          // n% 3 finds how many empty bottles are left after the n empty bottles have been replaced with some bottles of water, and then add 3, the total number of empty bottles that can be used to change water in the next round 
38  
39          return n / 3 + getNum (n% 3 + n / 3 );
 40      }
 41 }

 

Guess you like

Origin www.cnblogs.com/sun-/p/12676484.html