首页 > 解决方案 > 找到所需金额的最小货币数量

问题描述

我做了一个小程序来找到所需数量的最少纸币(货币)。例如,假设我输入了一个金额 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

标签: javascriptangulartypescriptfor-loopstackblitz

解决方案


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

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


推荐阅读