Javascript Coin changing / Change making algorithm

前端 未结 3 782
误落风尘
误落风尘 2021-01-25 19:24

So I\'ve been trying to create a program in Javascript/jQuery that splits an amount of money into the smallest amount of dollar bills. So far the program only works with one bil

3条回答
  •  故里飘歌
    2021-01-25 19:59

    var bills = [5, 10, 20, 50, 100];
    var money = mod(89);
    
    function mod(num){
        if (num % 5 === 0){
            return num;
        }else{
            return num + 5 - num % 5
        }
    }
    
    function foo(num){
        var index = bills.length - 1;
        var splits = [];
        while (money >= bills[0]){
            if (money >= bills[index]){
               money -= bills[index];
               splits.push(bills[index]);
            }else{
                index--;
            }
        }
        return splits;
    }
    
    console.log(foo(money));
    

    edited jsfiddle

提交回复
热议问题