有这样一道智力题:“某商店规定:三个空汽水瓶可以换一瓶汽水。小张手上有十个空汽水瓶,她最多可以换多少瓶汽水喝?”答案是5瓶,方法如下:先用9个空瓶子换3瓶汽水,喝掉3瓶满的,喝完以后4个空瓶子,用3个再换一瓶,喝掉这瓶满的,这时候剩2个空瓶子。然后你让老板先借给你一瓶汽水,喝掉这瓶满的,喝完以后用3个空瓶子换一瓶满的还给老板。如果小张手上有n个空汽水瓶,最多可以换多少瓶汽水喝?
当我看到这个问题,我认为应该用递归,因为换来的饮料喝完之后可能还牵扯多次换的情况,我的解决方法有两种。
一、可以理解为你每喝一瓶饮料都会少两个空瓶子,也就是递归减二。
#include"iostream"
using namespace std;
int Change(int x) {
int count = 0;
int a; //整数
int b; //余数
int c;
if (x <= 1) {
return 0;
} if (x == 2) {
count++;
return count;
}
else if (x >= 3) {
a = x / 3;
b = x % 3;
count = a + Change((x / 3) + (x % 3));
}
return count;
}
int main() {
int buy;
int total;
cin >> buy;
total = Change(buy);
cout << "cant change " << total << endl;
system("pause");
return 0;
}
二、每3个换一个,也可以用递归除3
#include <iostream>
using namespace std;
int Count(int n)
{
int empty = n; // 空瓶的个数
int ret = 0; // 返回喝的汽水数
while (empty)
{
// 一个瓶子直接退出循环
if (empty == 1)
break;
// 两个的话ret+1然后退出循环
if (empty == 2)
{
ret += 1;
break;
}
// value代表每次喝的汽水数
int value = empty / 3;
// 加上每次喝的汽水数
ret += value;
// 这两个是将空瓶的个数计数
empty %= 3;
empty += value;
}
return ret;
}
int main()
{
int n = 0;
// 循环输入遍历
while (cin >> n)
{ cout << Count(n) << endl;
}
return 0;
}