空瓶子换汽水问题

有这样一道智力题:“某商店规定:三个空汽水瓶可以换一瓶汽水。小张手上有十个空汽水瓶,她最多可以换多少瓶汽水喝?”答案是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;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值