我做了一个小程序来查找所需数量的最小纸币(货币)。例如,假设我输入金额1121 ,并且下面有一个包含这些值的数组: 笔记 = [1、2、5、10、50、100、200、500],所以我的最终结果将是:
500 * 2(notes)= 1000
100 * 1 = 100
20 * 1 = 20
1 * 1 = 1
则总数为 1121 。任何理解方面的帮助将不胜感激。我知道它只需要一个for循环,但是在某些方面我感到困惑。
这是我的工作:https://stackblitz.com/edit/angular-rufwzk?file=src%2Fapp%2Fapp.component.ts
答案 0 :(得分:0)
这是您想要的正确代码。我希望我做对了。
requiredNotes(amount) {
let noteArry = this.notes,
quotient,
remainder,
temp,
noteCount = 0,
eachNote,
remainingAmount = 0;
for (let i = noteArry.length - 1; i >= 0; i--) {
if (amount >= noteArry[i]) {
quotient = Math.floor(amount / noteArry[i]);
remainder = amount % noteArry[i];
amount = amount - (noteArry[i] * quotient);
if (amount == 0) {
console.log("note:-", noteArry[i], ",number of note", quotient);
break;
} else if (amount != 0) {
console.log("note:-", noteArry[i], ",number of note", quotient);
}
} else {
continue;
}
}
}
答案 1 :(得分:0)
for (let i = noteArry.length - 1; i >= 0; i--) {
if (amount >= noteArry[i]) {
quotient = Math.floor(amount / noteArry[i]);
remainder = amount % noteArry[i];
remainingAmount = noteArry[i] * quotient;
amount=amount-remainingAmount;
console.log('number of notes =', noteArry[i], 'x', quotient,' notes');
}
}
这样做的目的是简单地注销所提及数量的纸币数量。
答案 2 :(得分:0)
我简化了一些代码(使用JS Map):
...
notesMap = new Map();
...
requiredNotes(amount) {
for (let i = this.notes.length - 1; i >= 0 && amount; i--) {
const qty = Math.floor(amount / this.notes[i]);
qty && this.notesMap.set(this.notes[i], qty);
amount = amount % this.notes[i];
}
const entries = Array.from(this.notesMap.entries());
this.requireNotes = entries.map(([curr, qty]) => `${curr} * ${qty} = ${curr * qty}`);
}