输入一个月的预期工资,计算出最少纸币数量的组合方案,目前只学到顺序结构
其实,就是计算100,50,20,10,1的处理
你可以试试,有疑问来交流
private static Map<Float, Integer> greedyMoney(double total) {
Map<Float, Integer> map = new HashMap<>();
if (total == 0){
return map;
}
float[] moneys = new float[]{100, 50, 20, 10, 5, 1, 0.5f, 0.2f, 0.1f, 0.01f};
for (float money : moneys) {
int x = (int) (total / money);
if (x != 0) {
map.put(money, x);
}
total = total % money;
if (total == 0) {
break;
}
}
return map;
}
给你参考下。
import java.util.Scanner;
/*
问题描述:输入一个预期工资,得出最少的纸币数量
*/
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入工资:");
int money = sc.nextInt();
int money100 = money / 100 ;
int money50 = money % 100 / 50;
int money20 = money % 100 % 50 / 20;
int money10 = money % 100 % 50 % 20 /10;
int money5 = money %100 % 50 %20 %10 / 5;
int money2 = money %100 % 50 %20 %10 % 5 /2;
int money1 = money %100 % 50 %20 %10 % 5 % 2 / 1;
int count = money100 +money50 +money20 + money10 + money5 + money2 + money1;
System.out.println("总计纸币数量: " + count);
System.out.println("100面额纸币数量: " + money100);
System.out.println("50面额纸币数量: " + money50);
System.out.println("20面额纸币数量: " + money20);
System.out.println("10面额纸币数量: " + money10);
System.out.println("5面额纸币数量: " + money5);
System.out.println("2面额纸币数量: " + money2);
System.out.println("1面额纸币数量: " + money1);
}
}
贪婪算法 了解一下