Stepping Numbers | A C ++ program to find all the Stepping Number in [ n , m ] ; This function checks if an integer n is a Stepping Number ; Initalize prevDigit with - 1 ; Iterate through all digits of n and compare difference between value of previous and current digits ; Get Current digit ; Single digit is consider as a Stepping Number ; Check if absolute difference between prev digit and current digit is 1 ; A brute force approach based function to find all stepping numbers . ; Iterate through all the numbers from [ N , M ] and check if its a stepping number . ; Driver program to test above function ; Display Stepping Numbers in the range [ n , m ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isStepNum ( int n ) { int prevDigit = -1 ; while ( n ) { int curDigit = n % 10 ; if ( prevDigit == -1 ) prevDigit = curDigit ; else { if ( abs ( prevDigit - curDigit ) != 1 ) return false ; } prevDigit = curDigit ; n /= 10 ; } return true ; } void displaySteppingNumbers ( int n , int m ) { for ( int i = n ; i <= m ; i ++ ) if ( isStepNum ( i ) ) cout << i << " ▁ " ; } int main ( ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; return 0 ; }