java - 没有最低面值的货币面额组合
问题描述
可用面额 - 100s 50s & 20s 输入应能被 10 整除并大于 30。
我刚刚尝试了以下几乎所有尝试过的输入 - 我有办法减少/简化这个解决方案吗?
public class Sample {
private static void denomCalc(int userVal) {
input = userVal;
OrgAmt = input;
// Validate input for the available denominations 100s 50s and 20s
if (input == 30 || input < 20 || input % 10 != 0) {
return;
}
// check input against %100
OrgAmt = input % 100;
// Check if 100s are needed
if (input > 200) {
hundereds = (input / 100) - 1;
OrgAmt = input - hundereds * 100;
} else if (input > 100 && input < 200) {
if ((input % 100) % 50 == 0) {
hundereds = (input / 100);
OrgAmt = input - hundereds * 100;
fiftys = (OrgAmt / 50);
OrgAmt = OrgAmt % 50;
} else if ((input % 100) % 20 == 0) {
hundereds = (input / 100);
OrgAmt = input - hundereds * 100;
twenties = (OrgAmt / 20);
OrgAmt = OrgAmt % 20;
} else {
OrgAmt = input;
}
} else {
OrgAmt = input;
}
// Check if 50s are needed
if (OrgAmt % 50 < 20) {
fiftys = (OrgAmt / 50) - 1;
OrgAmt = OrgAmt - fiftys * 50;
} else if (OrgAmt % 50 > 20) {
// Check for 20s
if ((OrgAmt % 50) % 20 == 0) {
fiftys = (OrgAmt / 50);
OrgAmt = OrgAmt - fiftys * 50;
} else {
fiftys = (OrgAmt / 50) - 1;
OrgAmt = OrgAmt - fiftys * 50;
}
}
twenties = (OrgAmt / 20);
System.out.println(hundereds + " number of 100\'s");
System.out.println(fiftys + " number of 50\'s");
System.out.println(twenties + " number of 20\'s");
}
public static void main(String[] args) {
denomCalc(260);
}
}
解决方案
这是计算需要多少音符的一种不太复杂的方法。这是伪代码而不是语法上完美的 Java。运气好的话,它涵盖了所有(有效的)输入,这与我之前过于仓促的尝试不同。
// before this the input has been checked, as in OP's code
fifties = 0;
if (mod(input,20)==10) {
fifties = 1;
}
remainder = input - fifties*50;
// hundreds will be 0 if remainder is less than 100
hundreds = remainder / 100;
remainder = remainder-(hundreds*100);
twenties = remainder / 20;
// now print the results
推荐阅读
- android - ItemTouchHelper 的辅助功能
- multithreading - Java:启动线程的方法
- amazon-web-services - 启用 Elastic Bean Stalk 的 tomcat 日志文件的日志记录到 Cloudwatch
- python-3.x - 在我尝试为 kaggle 竞赛创建模型时出现“Tensorflow %s is not valid scope name error”
- r - gbm 无法识别调整参数网格
- reactjs - 需要脚本的绝对路径
- python - 使用 Python 将现有字典转换为 JSON
- azure - 运行容器化应用程序时的身份?
- magento2 - 未捕获的错误:找不到类“GuzzleHttp\Client”
- c# - C#如何访问NCrontab的非公共成员?