猿问

我如何进行这种更改方法,以便我收到给定金额的账单

我有一项任务,我必须将给定的金额分成账单。我看不出我做错了什么,因此请求一些指导。


export function change(amount) {


    var bills = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000];

    var result = [];


    while (amount > 0) {

        for (var i = 0; i < bills.length; i++) {

            if (amount >= bills[i]) {

                amount -= bills[i];

                result.push(bills[i]);

            }

        }

    }

    return result.length;

}


杨__羊羊
浏览 134回答 3
3回答

手掌心

您的代码会先检查较小的钞票,然后再检查较大的钞票,这显然是错误的:您希望在使用 1 美元钞票之前拥有尽可能多的 1000 美元钞票。因此,您可以反转帐单数组,或者只是对其进行排序以使其反转:function change(amount) {&nbsp; &nbsp; const bills = [1000, 500, 200, 100, 50, 20, 10, 5, 2, 1];&nbsp; &nbsp; // alternatively, to sort it&nbsp; &nbsp; // bills.sort((a, b) => b - a);&nbsp; &nbsp; const result = [];&nbsp; &nbsp; for (const bill of bills) {&nbsp; &nbsp; &nbsp; &nbsp; const billCount = Math.floor(amount / bill);&nbsp; &nbsp; &nbsp; &nbsp; amount = amount % bill;&nbsp; &nbsp; &nbsp; &nbsp; result.push(...new Array(billCount).fill(bill));&nbsp; &nbsp; }&nbsp; &nbsp; return result;}

www说

您的代码当前的问题在于它总是与第一个账单相关,而不是最大的账单。您需要找到适合给定金额的最大钞票,以最大限度地减少所需的钞票数量。假设您尝试change(100)使用当前的代码。它将评估帐单 1,看看它是否合适,然后继续处理帐单 2,当然它也合适。您当前的程序将重复bills作为输出,直到达到目标值。您可以通过bills向后迭代(从最大的开始)来解决此问题,或者您可以简单地反转它并保留当前的代码。这是一个稍微修改过的版本,修复了错误并使用了一些不错的现代 JS 功能。const change = function(amount) {&nbsp; &nbsp; const bills = [1000, 500, 200, 100, 50, 20, 10, 5, 2, 1];&nbsp; &nbsp; const result = [];&nbsp; &nbsp; while(amount > 0) {&nbsp; &nbsp; &nbsp; &nbsp; for(const bill of bills) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(amount >= bill) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount -= bill;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push(bill);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // You don't mention what the expected return value is, so completing this function is up to you&nbsp; &nbsp; // (...)&nbsp; &nbsp;&nbsp;};

喵喔喔

我编写了这段代码,如果您愿意,您可以重构它,但我认为这样就可以了function change (amount) {&nbsp; let change = {}&nbsp; let bills = [1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]&nbsp; if (amount > 0) {&nbsp; &nbsp; &nbsp;bills.map(bill => {&nbsp; &nbsp; &nbsp; &nbsp;if(amount > 0 && amount >= bill) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let value = amount / bill&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(amount % bill == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; change[bill.toString()] = value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount -= value * bill&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let remainder = amount % bill&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; change[bill.toString()] = ((value * bill) - remainder) / bill&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = remainder&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;});&nbsp; }&nbsp; return change}this.change(111)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答