การเพิ่มตัวเลขแบบโมโนโทน
จำนวนเต็มมีตัวเลขที่เพิ่มขึ้นแบบโมโนโทนก็ต่อเมื่อแต่ละคู่ของหลักที่อยู่ติดกัน x และ y ตรงตาม x <=y.
ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ตัวเลข num เป็นอาร์กิวเมนต์แรกและตัวเดียว
ฟังก์ชันของเราควรหาจำนวนที่มากที่สุดที่น้อยกว่าหรือเท่ากับ num ด้วยตัวเลขที่เพิ่มขึ้นแบบโมโนโทน
ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ
ป้อนข้อมูล
const num = 332;
ผลผลิต
const output = 299;
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const num = 332;
const monotoneIncreasingDigits = (num) => {
const checkMonotone = (x) =>{
if (x <= 9) {
return true
}
let currentDigit = x % 10
while (x) {
const next = Math.floor(x / 10)
const nextDigit = next % 10
if (currentDigit >= nextDigit) {
currentDigit = nextDigit
x = next
} else {
return false
}
}
return true
}
if (checkMonotone(num)) {
return num
}
const digits = num.toString().split('').map(x => Number(x))
return digits.reduce((acc, num, index) => {
if (num >= 1) {
const current = parseInt(digits.slice(0, index).join('') + num - 1 + new Array(digits.length - index - 1).fill('9').join(''), 10)
if (checkMonotone(current)) {
return Math.max(
acc,current)
}
}
return acc
}, 0)
}
console.log(monotoneIncreasingDigits(num)); ผลลัพธ์
299