เราจำเป็นต้องเขียนฟังก์ชัน 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