मोनोटोनिकली बढ़ते अंक
एक पूर्णांक के मोनोटोन बढ़ते अंक होते हैं यदि और केवल यदि आसन्न अंकों का प्रत्येक जोड़ा 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