-
Notifications
You must be signed in to change notification settings - Fork 1
/
JumpingNumber.cpp
64 lines (53 loc) · 1.62 KB
/
JumpingNumber.cpp
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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<long long> v; // Vector to store all Jumping numbers less than or equal to X.
// Prints all jumping numbers smaller than or equal to x starting
// with 'num'. It mainly does BFS starting from 'num'.
void bfs(long long x, long long num)
{
// Create a queue and enqueue 'i' to it
queue<long long> q;
q.push(num);
// Do BFS starting from i
while (!q.empty())
{
num = q.front();
q.pop();
if (num <= x)
{
v.push_back(num);
int last_dig = num % 10;
// If last digit is 0, append next digit only
if (last_dig == 0)
q.push((num * 10) + (last_dig + 1));
// If last digit is 9, append previous digit only
else if (last_dig == 9)
q.push((num * 10) + (last_dig - 1));
// If last digit is neighter 0 nor 9, append both
// previous and next digits
else
{
q.push((num * 10) + (last_dig - 1));
q.push((num * 10) + (last_dig + 1));
}
}
}
}
long long jumpingNums(long long X)
{
for (long long i = 1; i <= 9 && i <= X; i++)
bfs(X, i);
sort(v.begin(), v.end()); // Sort the vector of jumping numbers
return v[v.size() - 1]; // Return the last element
}
};
int main()
{
int x = 40;
Solution ob;
cout<<ob.jumpingNums(x);
return 0;
}