仅使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP