自写代码(递归实现)
#include <stdio.h>
int empty_bottle(int a)
{
if (a == 0)
{
return 0;
}
else
{
return 1 + empty_bottle(a - 1);
}
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = 0;
ret = n + empty_bottle(n);
printf("%d\n", ret);
return 0;
}
参考代码
/*
思路:
1. 20元首先可以喝20瓶,此时手中有20个空瓶子
2. 两个空瓶子可以喝一瓶,喝完之后,空瓶子剩余:empty/2(两个空瓶子换的喝完后产生的瓶子) + empty%2(不够换的瓶子)
3. 如果瓶子个数超过1个,可以继续换,即重复2
*/
int main()
{
int money = 0;
int total = 0;
int empty = 0;
scanf("%d", &money);
//方法1
total = money;
empty = money;
while(empty>1)
{
total += empty/2;
empty = empty/2+empty%2;
}
return 0;
}
// 方法二:按照上述喝水和用瓶子换的规则的话,可以发现,其实就是个等差数列:money*2-1
int main()
{
int money = 0;
int total = 0;
int empty = 0;
scanf("%d", &money);
//方法2
if(money <= 0)
{
total = 0;
}
else
{
total = money*2-1;
}
printf("total = %d\n", total);
return 0;
}