凑硬币(标号)

1.如何用1元,5元,10元,20元凑出任意的金额

		Scanner in = new Scanner(System.in);
		int amount = in.nextInt();
		for(int one = 0; one<=amount; ++one)
		{
			for(int five = 0; five<=amount/5; ++five)
			{
				for(int ten = 0; ten<=amount/10; ++ten)
				{
					for(int twenty=0; twenty<=amount/20; ++twenty)
					{
						if(one+five*5+ten*10+twenty*20==amount)
						{
							System.out.println(one+" 1R "+five+" 5R "+ten+" 10R "+twenty+" 20R ");
						}
					}
				}
			}
		}

这种算法会得到很多中答案

当我们只需要得到一种答案时

不能只用一个break;break只能跳出它那一层的循环。

法一

(多个break)

		Scanner in = new Scanner(System.in);
		int amount = in.nextInt();
		int isExit = 0;
		for(int one = 0; one<=amount; ++one)
		{
			for(int five = 0; five<=amount/5; ++five)
			{
				for(int ten = 0; ten<=amount/10; ++ten)
				{
					for(int twenty=0; twenty<=amount/20; ++twenty)
					{
						if(one+five*5+ten*10+twenty*20==amount)
						{
							System.out.println(one+" 1R "+five+" 5R "+ten+" 10R "+twenty+" 20R ");
							isExit = 1;
							break;
						}
					}
					if(isExit==1) break;
				}
				if(isExit==1) break;
			}
			if(isExit==1) break;
		

法二(标号)

		Scanner in = new Scanner(System.in);
		int amount = in.nextInt();
		OUT:
		for(int one = 0; one<=amount; ++one)
		{
			for(int five = 0; five<=amount/5; ++five)
			{
				for(int ten = 0; ten<=amount/10; ++ten)
				{
					for(int twenty=0; twenty<=amount/20; ++twenty)
					{
						if(one+five*5+ten*10+twenty*20==amount)
						{
							System.out.println(one+" 1R "+five+" 5R "+ten+" 10R "+twenty+" 20R ");
							break OUT;
						}
					}
				}
			}
		}

		

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值