Skip to content

Commit 239f213

Browse files
committed
1291
1 parent b21fb2f commit 239f213

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# [1291. Sequential Digits (Medium)](https://leetcode.com/problems/sequential-digits/)
2+
3+
<p>An&nbsp;integer has <em>sequential digits</em> if and only if each digit in the number is one more than the previous digit.</p>
4+
5+
<p>Return a <strong>sorted</strong> list of all the integers&nbsp;in the range <code>[low, high]</code>&nbsp;inclusive that have sequential digits.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong>Example 1:</strong></p>
9+
<pre><strong>Input:</strong> low = 100, high = 300
10+
<strong>Output:</strong> [123,234]
11+
</pre><p><strong>Example 2:</strong></p>
12+
<pre><strong>Input:</strong> low = 1000, high = 13000
13+
<strong>Output:</strong> [1234,2345,3456,4567,5678,6789,12345]
14+
</pre>
15+
<p>&nbsp;</p>
16+
<p><strong>Constraints:</strong></p>
17+
18+
<ul>
19+
<li><code>10 &lt;= low &lt;= high &lt;= 10^9</code></li>
20+
</ul>
21+
22+
23+
**Related Topics**:
24+
[Backtracking](https://leetcode.com/tag/backtracking/)
25+
26+
## Solution 1.
27+
28+
```cpp
29+
// OJ: https://leetcode.com/problems/sequential-digits/
30+
// Author: github.com/lzl124631x
31+
// Time: O(1) since there are limited number of valid integers
32+
// Space: O(1)
33+
class Solution {
34+
long get(int start, int len) {
35+
long ans = 0;
36+
while (len-- > 0) {
37+
ans = ans * 10 + start;
38+
++start;
39+
}
40+
return ans;
41+
}
42+
public:
43+
vector<int> sequentialDigits(int low, int high) {
44+
vector<int> ans;
45+
int len = 0, tmp = len;
46+
while (tmp) {
47+
tmp /= 10;
48+
++len;
49+
}
50+
while (len <= 9) {
51+
for (int i = 1; i <= 9 - len + 1; ++i) {
52+
long long n = get(i, len);
53+
if (n < low) continue;
54+
if (n > high) return ans;
55+
ans.push_back(n);
56+
}
57+
++len;
58+
}
59+
return ans;
60+
}
61+
};
62+
```

0 commit comments

Comments
 (0)