Java编程:最少钱币数,这是一个古老而又经典的问题,用给定的几种钱币

Java编程:最少钱币数,这是一个古老而又经典的问题,用给定的几种钱币,第1张

/**

* 简单用人民币的常见数额做了初始化

*/

public class Test {

public static void main(String[] args){

int[] commonMoney = {100,50,20,10,5,1}

System.out.println(getLeastNum(108,commonMoney))

}

static String getLeastNum(int targetMoney,int[] commonMoney){

StringBuffer buffer = new StringBuffer()

int num = 0,total = 0

String result = targetMoney + "$ 最少需要 "

for(int money : commonMoney){

if(targetMoney >= money){

total += num = targetMoney/money

targetMoney = targetMoney%money

buffer.append(","雹笑孝升销 + num + " 张 " + money + "源稿$")

}

if(0 == targetMoney) break

}

return result + total + " 张货币,分别是: " + buffer.substring(1)

}

}

输出:

108$ 最少需要 5 张货币,分别是: 1 张 100$,1 张 5$,3 张 1$

import java.util.*

public class test {

/**

* @param args

*/

int a,b,c,d,e

int result

int sum

public static void main(String[] args) {

test test1 = new test()

Scanner sc = new Scanner(System.in)

System.out.println("请输入数值")

test1.count(sc.nextInt())

}

public void count(int target)

{

ArrayList<Integer>sumList = new ArrayList<Integer>()

for(a=0a<targeta++)

{

for(b=0b<=(target/100)b++)

{

for(c=0c<=2c++)

{

for(d=0d<=2d++)

{

for(e=0e<=10e++)

{

result=100*a+50*b+20*c+10*d+e

if(result==target)

{

sum=a+b+c+d+e

sumList.add(sum)

System.out.println("100元"+a+"张"+"50元"+b+"张"+"20元"+c+"张"+"10元竖茄"+d+"张"+"1元"+e+"张. 一共用了"+sum+"张")

}

}

}

}

}

}

System.out.print("用张数最少为"+Collections.min(sumList))

}

}

////////////////用5个循环就OK了,递归反而麻烦.

输出结果为

请输入数值

528

100元3张50元4张20元0张10元2张1元8张. 一共用了17张

100元3张50元4张20元1张10元0张1元8张. 一共用了16张

100元4张50元2张信纤指20元0张10元2张1元8张. 一共用了16张

100元4张50元2张20元1张10元0张1元8张. 一共用了15张

100元5张50元0张20元0张10元2张1元8张. 一共用了15张

100元5张50元0张20元1张10元滑配0张1元8张. 一共用了14张

用张数最少为14

楼主记得加分哈~~


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12511186.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-26
下一篇 2023-05-26

发表评论

登录后才能评论

评论列表(0条)

保存