【发布时间】:2017-07-17 07:48:38
【问题描述】:
将给定金额更改为最小钞票数量。
输入: 金额:正整数; 票据:不同正整数的排序列表(例如 [1, 5, 10])。
假设: 金额不超过100。 最多 4 个钞票面值。
如果无法更改金额,则必须返回 0。
示例: 金额:17,账单:[1,5,10],答案:4 -> 10+5+1+1 金额:17,账单:[2, 4],答案:0
这是我目前的代码
function sort(array) {
for (var i = array.length - 1; i >= 0; i--) {
for (var j = 0; j < i; j++) {
if (array[j + 1] > array[j]) {
var z = array[j];
array[j] = array[j + 1];
array[j + 1] = z;
}
}
}
return array;
}
function change(amount, bills) {
sort(bills);
var result = [];
while (amount > 0) {
for (var i = 0; i < bills.length; i++) {
if (amount >= bills[i]) {
amount -= bills[i];
result.push(bills[i]);
i--;
}
}
}
return result.length;
}
console.log(change(17, [1, 5, 10])); // Expect: 4
console.log(change(17, [2, 4])); // Expect: 0
console.log(change(18, [2, 4])); // Expect: 5
//console.log(change(17, [3, 5])); // Expect: 5
有两个问题 一个是如果金额不能被分割,它不会返回 0,而只是滞后,因为它是一个无限循环。 其次是在最后一个例子中,17,[3,5] 我的代码取了 5 3 次,然后意识到它不能做剩下的 2 并且滞后,而不是做 3 4 次并添加 5。
非常感谢建议或修复代码。请保持相当简单,我只是一个初学者。
【问题讨论】:
标签: javascript function coin-change