Sequential digits numbers are rare and can be generated by starting from each digit 1-9 and appending the next digit until 9. We can enumerate all such numbers and filter those in the given range.
classSolution {
public: vector<int> sequentialDigits(int low, int high) {
vector<int> ans;
for (int len = to_string(low).size(); len <= to_string(high).size(); ++len) {
for (int start =1; start <=10- len; ++start) {
int num =0;
for (int d =0; d < len; ++d) num = num *10+ (start + d);
if (num >= low && num <= high) ans.push_back(num);
}
}
sort(ans.begin(), ans.end());
return ans;
}
};
import java.util.*;
classSolution {
public List<Integer>sequentialDigits(int low, int high) {
List<Integer> ans =new ArrayList<>();
int minLen = String.valueOf(low).length(), maxLen = String.valueOf(high).length();
for (int len = minLen; len <= maxLen; ++len) {
for (int start = 1; start <= 10 - len; ++start) {
int num = 0;
for (int d = 0; d < len; ++d) num = num * 10 + (start + d);
if (num >= low && num <= high) ans.add(num);
}
}
Collections.sort(ans);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsequentialDigits(low: Int, high: Int): List<Int> {
val ans = mutableListOf<Int>()
val minLen = low.toString().length
val maxLen = high.toString().length
for (len in minLen..maxLen) {
for (start in1..(10-len)) {
var num = 0for (d in0 until len) num = num * 10 + (start + d)
if (num in low..high) ans.add(num)
}
}
ans.sort()
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defsequentialDigits(self, low: int, high: int) -> list[int]:
ans = []
for l in range(len(str(low)), len(str(high)) +1):
for start in range(1, 11- l):
num =0for d in range(l):
num = num *10+ start + d
if low <= num <= high:
ans.append(num)
ans.sort()
return ans
impl Solution {
pubfnsequential_digits(low: i32, high: i32) -> Vec<i32> {
letmut ans =vec![];
let min_len = low.to_string().len();
let max_len = high.to_string().len();
for len in min_len..=max_len {
for start in1..=(10-len) {
letmut num =0;
for d in0..len {
num = num *10+ (start + d) asi32;
}
if num >= low && num <= high {
ans.push(num);
}
}
}
ans.sort();
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
sequentialDigits(low: number, high: number):number[] {
constans: number[] = [];
constminLen=low.toString().length, maxLen=high.toString().length;
for (letlen=minLen; len<=maxLen; ++len) {
for (letstart=1; start<=10-len; ++start) {
letnum=0;
for (letd=0; d<len; ++d) num=num*10+start+d;
if (num>=low&&num<=high) ans.push(num);
}
}
ans.sort((a, b) =>a-b);
returnans;
}
}