From 5a8c9c4abdc49898ea5861fc76e4661d02b44808 Mon Sep 17 00:00:00 2001 From: stuti-v4 <70504325+stuti-v4@users.noreply.github.com> Date: Thu, 1 Oct 2020 14:04:08 +0530 Subject: [PATCH] Created a Stepping number Graph algo --- graph_algos/Stepping Number.cpp | 60 +++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 graph_algos/Stepping Number.cpp diff --git a/graph_algos/Stepping Number.cpp b/graph_algos/Stepping Number.cpp new file mode 100644 index 0000000..e9d3aab --- /dev/null +++ b/graph_algos/Stepping Number.cpp @@ -0,0 +1,60 @@ +// A C++ program to find all the Stepping Number in [n, m] +#include +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,m; + cout<<"Enter the range of the numbers : "; + cin>>n>>m; + + // Display Stepping Numbers in + // the range [n, m] + cout<<"the Stepping numbers are :"; + displaySteppingNumbers(n, m); + + return 0; +}