-1

我做了一个小程序来找到所需数量的最少纸币(货币)。例如,假设我输入了一个金额 1121,并且我有以下这些值的数组: notes = [1, 2, 5, 10, 50, 100, 200, 500] 所以我的最终结果将是:

500 * 2(注)= 1000

100 * 1 = 100

20 * 1 = 20

1 * 1 = 1

那么总数将是1121。任何有助于理解的帮助将不胜感激。我知道它只需要一个 for 循环,但我在某些部分感到困惑。

这就是我所做的:https ://stackblitz.com/edit/angular-rufwzk?file=src%2Fapp%2Fapp.component.ts

4

3 回答 3

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');
  }
}

这样做的诀窍是简单地记录所提到数量的音符数量。

于 2018-09-15T19:29:37.567 回答
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}`);
}

堆栈闪电战

于 2018-09-15T19:51:09.963 回答
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;
      }
    }
  }
于 2018-09-15T19:17:04.430 回答