JavaScript 中具有单调数字的较小数字
javascriptweb developmentfront end technology
单调递增数字
当且仅当每对相邻数字 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