在 JavaScript 中查找一个范围内的顺序数字
顺序数字
一个数字只有当且仅当数字中的每个数字比前一个数字多 1 时才具有顺序数字。
问题
我们要求编写一个 JavaScript 函数,该函数采用一个包含正好两个元素并指定一个范围的数组 arr。
我们的函数应该返回一个已排序的数组,其中包含 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP