僅使用 JavaScript 中的單調數字的較小數字


單調遞增數字

當且僅當每一對相鄰數字 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

更新時間:2021 年 4 月 24 日

109 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告