用贪心算法解决金钱兑换问题(基于JAVA)

货币的流通是最频繁的事情之一了,为方便流通很多时候需牵涉到各种面值货币间的等值交换。在实际生活中,由于货币本身的特点,我们不可能总是用一张钱币来满足我们的不同需求。对于任意一个金额,我们能用最少的钱币数目组合得到是一件有趣的事情。下面用贪心算法实现之。


程序源代码:

import java.io.*;


public class MoneyCount
{
public static void main(String[] args)
{
int[] val = {100, 50, 20, 10, 5, 2, 1}; //假设现有不同面值的钱币有7种
int count;
int[] num = new int[7]; //用数组存储在最佳组合的情况下各种面值货币的数目
int asval = 0;
System.out.println("Please input the total money to count.");
try //异常处理
{
InputStreamReader reader = new InputStreamReader(System.in); //可以让用户输入任意一个金额,因此定义输入流对象
BufferedReader input = new BufferedReader(reader);
asval = Integer.parseInt(input.readLine()); //读入一个字符串并转化成整型数值
}
catch(NumberFormatException nfe) //当字符串转化为整型数值时出错使捕获异常
{
System.out.println("NumberFormatException occur: " + nfe.getMessage());
}
catch(IOException ioe) //输入输出错误捕获异常
{
System.out.println("IOException occur: " + ioe.getMessage());
}
if(asval != 0)
{
int reval = asval;
for(int i = 0; i < 7; i++) //贪心算法求最佳组合
{
num[i] = asval / val[i];
asval = asval % val[i];
}
System.out.println("Your total money is " + reval + ", and you can get the best combination ");
for(int i = 0; i < 7; i++)
{
if(num[i] != 0)System.out.println("The number of " + val[i] + " is " +  num[i]);
}
}
}

}


示例输出:

Please input the total money to count.
354
Your total money is 354, and you can get the best combination
The number of 100 is 3
The number of 50 is 1
The number of 2 is 2

即对于354的金额数给出的最佳组合是3张100的, 1张50的和2个2的

你可能感兴趣的:(用贪心算法解决金钱兑换问题(基于JAVA))