試圖解決這個Codewars 挑戰。您有一個由數字組成的正數 n。您最多可以執行一個操作:選擇數字中某個數字的索引,在該索引處刪除該數字并將其插入到另一個或數字中的同一位置,以便找到您可以獲得的最小數字。任務:根據語言返回數組或元組或字符串(請參閱“示例測試”):1)你得到的最小數字2)你取的數字d的索引i,i越小越好3) 插入這個數字 d 以獲得最小數字的索引 j(盡可能?。?。例子:smallest(261235) --> [126235, 2, 0] or (126235, 2, 0) or "126235, 2, 0"其他例子:209917, [29917, 0, 1]285365, [238565, 3, 1]269045, [26945, 3, 0]296837, [239687, 4, 1]因此,為了獲得盡可能小的數字,我們需要從數字中刪除最小的數字并將其放在數字的前面,對嗎?function smallest (n) { //turn n into an array let array = String(n).split("").map(Number); let smallest = Math.min(...array); //find index of smallest in original array let index = array.indexOf(smallest); //remove smallest from original array, move it to front array.splice(index, 1); array.unshift(smallest); let newNumber = Number(array.join("")); //return array of new number, index of where the smallest was, //and index of where the smallest is now return ([newNumber, index, 0]);}console.log(smallest(239687));我的答案是返回正確的數字,但是,大約有一半的時間,它沒有返回正確的 indexi和 index j。
找到最小的 - Codewars 挑戰 - Javascript
LEATH
2021-07-02 14:00:30