-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJumpingNumbers.cpp
More file actions
78 lines (67 loc) · 1.44 KB
/
JumpingNumbers.cpp
File metadata and controls
78 lines (67 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <queue>
// QUESTION: https://www.geeksforgeeks.org/print-all-jumping-numbers-smaller-than-or-equal-to-a-given-value/
class JumpingNumberGenerator
{
private:
std::vector<int> numbers;
private:
void bfs(int start, int target)
{
std::queue<int> queue;
queue.push(start);
while (!queue.empty())
{
int top = queue.front();
queue.pop();
if (top < target)
{
numbers.push_back(top);
// Get the last digit
int last_digit = top % 10;
if (last_digit == 0)
{
// you can't go in the left direction
queue.push(10 * top + (last_digit + 1));
} else if (last_digit == 9) {
// you can't go in the right direction
queue.push(10 * top + (last_digit - 1));
} else {
// you can go in both directions
queue.push(10 * top + (last_digit - 1));
queue.push(10 * top + (last_digit + 1));
}
}
}
}
public:
void generate(int input)
{
// Push 0 onto the result
if (input > 0)
numbers.push_back(0);
// Do a level-wise traveral for all single digit numbers, to get
// multiple digits
for (int i = 1; i <= 9; ++i)
{
if (i < input)
bfs(i, input);
}
}
void print()
{
std::cout << "There are " << numbers.size() << " jumping numbers are" << std::endl;
for (auto iter : numbers)
{
std::cout << iter << std::endl;
}
}
};
int main()
{
JumpingNumberGenerator obj;
obj.generate(105);
obj.print();
return 0;
}