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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短