순차 숫자
숫자의 각 숫자가 이전 숫자보다 하나 더 많은 경우에만 숫자에 연속 숫자가 있습니다.
문제
범위를 지정하는 정확히 두 요소의 배열(arr)을 취하는 JavaScript 함수를 작성해야 합니다.
우리 함수는 arr 범위(제한 포함)에 있는 모든 정수의 정렬된 배열을 반환해야 하며, 이 배열은 숫자가 연속적입니다.
예를 들어, 함수에 대한 입력이 -
인 경우const arr = [1000, 13000];
그러면 출력은 다음과 같아야 합니다. -
const output = [1234, 2345, 3456, 4567, 5678, 6789, 12345];
예시
이에 대한 코드는 -
const arr = [1000, 13000];
const sequentialDigits = ([low, high] = [1, 1]) => {
const findCount = (num) => {
let count = 0;
while(num > 0){
count += 1
num = Math.floor(num / 10)
};
return count;
};
const helper = (count, start) => {
let res = start;
while(count > 1 && start < 9){
res = res * 10 + start + 1;
start += 1;
count -= 1;
};
if(count > 1){
return 0;
};
return res;
};
const count1 = findCount(low);
const count2 = findCount(high);
const res = [];
for(let i = count1; i <= count2; i++){
for(let start = 1; start <= 8; start++){
const num = helper(i, start);
if(num >= low && num <= high){
res.push(num);
};
};
};
return res;
};
console.log(sequentialDigits(arr)); 출력
콘솔의 출력은 -
[ 1234, 2345, 3456, 4567, 5678, 6789, 12345 ]