JavaScript 中數字可能的最大位數差


我們需要編寫一個 JavaScript 函式,該函式需要一個數字。然後,該函式應返回該數字的任意兩個位數之間存在的最大差值。

換句話說,該函式只應返回其中存在最大和最小位數之間的差值。

例如

If the number is 654646,
Then the smallest digit here is 4 and the greatest is 6
Hence, our output should be 2

示例

此程式碼將為 −

const num = 654646;
const maxDifference = (num, min = Infinity, max = -Infinity) => {
   if(num){
      const digit = num % 10;
      return maxDifference(Math.floor(num / 10), Math.min(digit, min),
      Math.max(digit, max));
   };
   return max - min;
};
console.log(maxDifference(num));

輸出

控制檯中輸出的 −

2

更新於: 15-Oct-2020

113 次觀看

開啟您的 職業生涯

完成課程並獲得認證

開始學習
廣告