Just smaller number with monotone digits in JavaScript

JavascriptWeb DevelopmentFront End Technology

Monotonically Increasing Digits

An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.

Problem

We are required to write a JavaScript function that takes in a number, num, as the first and the only argument.

Our function should simply find the largest number that is less than or equal to num with monotone increasing digits.

For example, if the input to the function is

Input

const num = 332;

Output

const output = 299;

Example

Following is the code −

 Live Demo

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));

Output

299
raja
Published on 24-Apr-2021 10:09:32
Advertisements