亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

查找總和為給定數量數組問題的最小紙幣和值的數量

查找總和為給定數量數組問題的最小紙幣和值的數量

慕的地8271018 2021-12-23 20:00:37
當我嘗試獲取此值 2316 時,它的返回值 [0,2,0,3,0,0,2,1,0,1] 但我需要將其輸出 [0,2,0,3,0,0, 1,1,0,1] 我認為我的算法有問題。function findNoteAndCoins(salary) {  var note = [5000,1000,500,100,50,20,10,5,2,1];  var noteCount = new Array(10);  noteCount = Array.from(noteCount, item => item || 0);    for(var i = 0; i < 10; i++){        if (salary >= note[i]){            noteCount[i]= salary / note[i];            salary = salary % note[i];        }    }   for(var j = 0; j < 10; j++){        if (noteCount[j] != 0){            var count = noteCount[j];        }    }  return noteCount.map(num => (num * 1).toFixed(0));  }findNoteAndCoins(2316);
查看完整描述

1 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

要將音符的浮點數轉換為整數,請使用Math.trunc或Math.floor:Math.trunc(remaining / note)


整個代碼看起來像:


function findNoteAndCoins(salary) {

  const notes = [5000, 1000, 500, 100, 50, 20, 10, 5, 2, 1];

  const notesCount = [];


  let remaining = salary;

  for (const note of notes) {

    if (salary >= note) {

      notesCount.push(Math.trunc(remaining / note));

      remaining = remaining % note;

    } else {

      notesCount.push(0);

    }

  }


  return notesCount;

}


console.log(findNoteAndCoins(2316));

我們可以檢查該findNoteAndCoins函數是否有效:


function findSalary(notesCount) {

  const notes = [5000, 1000, 500, 100, 50, 20, 10, 5, 2, 1];

  let salary = 0;

  for (let i = 0; i < notesCount.length; i++) {

    salary += notesCount[i] * notes[i];

  }

  return salary;

}


console.log(findSalary(findNoteAndCoins(2316)) === 2316);


查看完整回答
反對 回復 2021-12-23
  • 1 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號