-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStepping Numbers
56 lines (48 loc) · 1.33 KB
/
Stepping Numbers
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
#include<bits/stdc++.h>
using namespace std;
// This function checks if an integer n is a Stepping Number
bool isStepNum(int n)
{
// Initalize prevDigit with -1
int prevDigit = -1;
// Iterate through all digits of n and compare difference
// between value of previous and current digits
while (n)
{
// Get Current digit
int curDigit = n % 10;
// Single digit is consider as a
// Stepping Number
if (prevDigit == -1)
prevDigit = curDigit;
else
{
// Check if absolute difference between
// prev digit and current digit is 1
if (abs(prevDigit - curDigit) != 1)
return false;
}
prevDigit = curDigit;
n /= 10;
}
return true;
}
// A brute force approach based function to find all
// stepping numbers.
void displaySteppingNumbers(int n, int m)
{
// Iterate through all the numbers from [N,M]
// and check if it’s a stepping number.
for (int i=n; i<=m; i++)
if (isStepNum(i))
cout << i << " ";
}
// Driver program to test above function
int main()
{
int n = 0, m = 21;
// Display Stepping Numbers in
// the range [n, m]
displaySteppingNumbers(n, m);
return 0;
}