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