Skip to content

Commit 588acbf

Browse files
authored
Create solution.cpp
1 parent 710d638 commit 588acbf

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

LexicographicalNumbers/solution.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public:
3+
4+
vector<int> lexicalOrder(int n)
5+
{
6+
vector<int> lexicalNums;
7+
8+
int num = 1;
9+
for (int i=0; i<n; i++)
10+
{
11+
lexicalNums.push_back(num);
12+
13+
if (num * 10 <= n)
14+
{
15+
// move on to next digit/level in lexicographical order
16+
num *= 10;
17+
}
18+
else
19+
{
20+
// go back to parent node if num exceeds n
21+
if (num >= n)
22+
num /= 10;
23+
24+
// increment to next num
25+
num++;
26+
27+
// remove trailing zeros
28+
while (num % 10 == 0)
29+
num /= 10;
30+
}
31+
}
32+
33+
return lexicalNums;
34+
}
35+
};

0 commit comments

Comments
 (0)