【问题标题】:Change given amount of money to bills将给定金额更改为账单
【发布时间】: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


    【解决方案1】:

    如果修复了您的更改功能并添加了 cmets 来解释我的更改,如果您有任何疑问,请告诉我

    function change (amount, bills) {
        //Asign sorted array of bills to possibleBills
        var possibleBills = sort(bills);
    
        var result = [];
    
        //Asign amount to currentAmount
        var currentAmount = amount;
    
        //Sort through possibleBills
        for (var i = 0; i < possibleBills.length; i++) {
            //Perform action inside while loop if the current bill value can be substracted from currentAmount
            while (currentAmount - possibleBills[i] >= 0) {
    
                currentAmount -= possibleBills[i];
                result.push(possibleBills[i]);
    
                //End loop and return the length of result if currentAmount reaches 0
                if (currentAmount === 0) {
                    return result.length;
                }
            }
        }
    
        //Return 0 if the amount couldn't be changed with the given bills
        if (currentAmount > 0) {
            return 0;
        }
    
    
        return result.length;
    };
    

    【讨论】:

    • 效果比我的好,但还是有上一个的问题。使用 17, [3,5] 它返回 0 好像它不能这样做,但可以通过 4 3s 和 1 5
    • 代码中的cmets 应该解释为什么代码正在做它正在做的事情。当代码更好地解释自己时,看到人们把 cmets 到处解释代码正在做的事情真的很烦人
    • 如果您真的阅读了我写的内容,而不仅仅是愤怒的评论。你会注意到我是首发。 Larpee 很好地考虑到了这一点,并添加了 cmets,以便我了解他在做什么。它帮助了我,我不知道你为什么为此生气。
    • @Mendal 我很高兴能帮上忙。我不确定如何解决最后一个问题,对不起
    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 2015-02-04
    • 2013-09-22
    • 2019-09-05
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多