Drink soda, 1 bottles of soda 1 yuan, 2 empty bottles can change a bottle of soda, to 20 yuan, how much soda can. Programmatic implementation.
The whole idea : a recursive way to achieve, each recursive means that this time can buy soda bottle number (M). First of all, to determine whether M is able to fully redeem (m even), in two cases:
If can (M is even), again m/2 recursion, means this time m a bottle to Exchange M/2 soda;
If it is not possible (M is odd), here we make a judgment (flag: see if there is an empty bottle in the exchange before the exchange, the initial value is 0, if the flag is 0 (no excess), then this exchange leaves an empty bottle, namely flag=1 (this time leave a not to exchange), For the next exchange, if the flag is 1, then this exchange, plus this bottle, for the exchange, that is, Flag=0, said that the empty bottles had been used out.
Until the 2*M + flag is less than 2, can not be redeemed so far.
Code implementation (Visual Studio 2017)
//drink soda, 1 bottles of soda 1 yuan, 2 empty bottles can change a bottle of soda, to 20 yuan, how much soda can.
Programmatic implementation. #include <stdio.h> #include <windows.h> int buysoda (int M) {static int flag = 0;//flag as a judgment, see in the exchange before this exchange is
Whether there is an excess cap if (2 * M + flag < 2)//To determine whether soda can be purchased {return 0;
if (m% 2 = 0) The bottle top of//m bottle soda is even, the exchange just changed {return M + Buysoda (M/2); else if (M% 2 = 1 && flag = 0) The cap of//m bottle soda is odd, and there is no excess cap, leaving a bottle cap, the rest is all convertible {flag = 1;//means that the exchange is left with a bottle cap,
Provide the next Exchange return M + Buysoda (M/2);
else if (M% 2 = 1 && flag = 1) The cap of//m bottle soda is odd and has an extra bottle cap, plus this cap is exchanged with the lid of {flag = 0;//before the cap has been used out
return M + Buysoda (M/2 + 1);
int main () {int money = 20;
int num = 0;
num = Buysoda (money);
printf ("Can buy%d bottles of soda \ n", num);
System ("pause");
return 0; }