একঘেয়ে সংখ্যা বৃদ্ধি
একটি পূর্ণসংখ্যার একঘেয়ে সংখ্যা বৃদ্ধি পায় যদি এবং শুধুমাত্র যদি প্রতিটি জোড়া সন্নিহিত সংখ্যা x এবং y সন্তুষ্ট করে x <=y।
সমস্যা
আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা প্রথম এবং একমাত্র যুক্তি হিসাবে একটি সংখ্যা, সংখ্যা নেয়৷
আমাদের ফাংশনটি কেবলমাত্র সবচেয়ে বড় সংখ্যাটি খুঁজে বের করতে হবে যা একঘেয়ে ক্রমবর্ধমান সংখ্যার সাথে সংখ্যার চেয়ে কম বা সমান।
উদাহরণস্বরূপ, যদি ফাংশনে ইনপুট হয়
ইনপুট
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