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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP