【问题标题】:find minimum numbers of currency for required amount找到所需金额的最小货币数量
【发布时间】:2019-02-20 04:51:50
【问题描述】:

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

【问题讨论】:

  • 您的代码有什么问题?我不确定问题是什么......
  • 您对哪些部分感到困惑?
  • 我想存储每个值的数量及其商,以检查它是否等于输入的数量输入的数量: 1121 array = [1, 2, 5, 10、50、100、200、500];从反向开始 1) 1121 / 500 = 500 * 2 = 1000,余数 121 和商是 2 2) 121 / 200 不可​​能 3) 121 / 100 = 100 * 1 = 100,余数 21 和商是 1 4) 21 / 50 不可能 5) 21 / 10 = 10 * 2 = 20, 余数为 1 商 2 6) 1 / 5 不可能 我的最终结果是哪种纸币:500、100、10 每种货币的数量:2、1、 2(商)
  • @user184994 我的问题是我想控制每张纸币及其重复数字。将数组视为货币数组。例如输入金额 1000 然后我需要 500rs 票据 2 次。
  • @confusedGuy 请输入您帖子中的所有解释。

标签: javascript angular typescript for-loop stackblitz


【解决方案1】:
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】:

我简化了一点你的代码(使用 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}`);
}

STACKBLITZ

【讨论】:

    【解决方案3】:

    这是您想要的更正代码。我希望我做对了。

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

    【讨论】:

    • 是的,完全正确。就这么简单。现在我觉得自己很愚蠢。谢谢一堆。我真的被困在了剩余金额部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2020-11-26
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多