如何在 JavaScript 中最多隻交換一次就找到最大的數字


我們需要編寫一個 JavaScript 函式,它將數字作為第一個和唯一的引數輸入。

我們函式的任務是在數字的任意兩個數字之間執行至多一次交換,併產生可能的最大數字。但是,如果該數字已經是可能的最大數字,則我們應返回該數字本身。

例如 −

如果輸入數字為 −

const num = 1625;

則輸出應為 −

const output = 6125;

我們交換了 1 和 6,這是在單次交換中產生最大數字的唯一交換

示例

程式碼如下 −

 現場演示

const num = 1625;
const findMaximumDigit = (num, max = 0) => {
   if(!num){
      return max;
   };
   return findMaximumDigit(Math.floor(num / 10), Math.max(max, num %10));
};
const makeOneSwap = (num = 1) => {
   let i = 0;
   const max = findMaximumDigit(num);
   const numStr = String(num);
   const numArr = numStr.split('');
   const maxIndex = numStr.lastIndexOf('' + max);
   while(i < maxIndex){
      if(+numStr[i] < max){
         let temp = numArr[i];
         numArr[i] = numArr[maxIndex];
         numArr[maxIndex] = temp;
         break;
      };
   };
   return +(numArr.join(''));
};
console.log(makeOneSwap(num));

輸出

控制檯中的輸出將為 −

6125

更新於: 03-Mar-2021

186 次瀏覽

啟動您的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.