【CodeWars】Next bigger number with the same digits
阿新 • • 發佈:2021-10-18
參考:https://www.geeksforgeeks.org/find-next-greater-number-set-digits/
const given_number = 320235484882472; // 大腦理解就是4變成6然後+479(4、7、9組合成的最小數字) // 演算法理解就是從右到左找,找到第一個可以被替換的數字->4。 // 7>6,7不行。9>7,9不行。4<9,4可以 // 找到[9,7,6]裡面最小的數字6 // 交換4和6。就固定好了最高位536 // 剩下的數字排序,結果就是最小的數字479 const nextBigger=(number)=>{ const arr=(number+'').split('').map((item)=>Number(item)); const len=arr.length; const tempArr=[]; const map={}; const result=[]; // 從右到左,找到需要被交換的數字 for(var i=len-1;i>=0;i--){ tempArr.push(arr[i]); if((i!=len-1)&&(arr[i]<arr[i+1])){ map.replacedNum=arr[i]; map.replacedIndex=i; break; } } if(map.replacedNum===undefined){ return -1 } // 找到和他交換的大數字,通過計算得到這個數字在原陣列中的index tempArr.pop(); tempArr.reverse(); map.biggerNum=tempArr[0]; tempArr.forEach((item,index)=>{ if((item>map.replacedNum)&&(item <= map.biggerNum)){ map.biggerNum=item; map.biggerNumIndex=index; } }); map.biggerNumIndex= map.biggerNumIndex+map.replacedIndex+1; console.log(tempArr) // 交換 arr.forEach((item,index)=>{ if(index===map.replacedIndex){ result.push(map.biggerNum); }else if(index===map.biggerNumIndex){ result.push(map.replacedNum); }else{ result.push(item) } }); arr.splice(map.biggerNumIndex,1,map.replacedNum) // replacedIndex之後的數字全部重新排序,排成最小的數字就行 const newNumArr=arr.slice(map.replacedIndex+1).sort(); result.splice(map.replacedIndex+1); return Number(result.concat(newNumArr).join('')); } const res=nextBigger(given_number); console.log(res)