단조 증가하는 자릿수
정수는 인접한 숫자 x와 y의 각 쌍이 x <=y를 충족하는 경우에만 모노톤 증가 숫자를 갖습니다.
문제
첫 번째이자 유일한 인수로 숫자 num을 취하는 JavaScript 함수를 작성해야 합니다.
우리 함수는 단순하게 증가하는 자릿수로 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