 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all Jumping Numbers smaller than or equal to a given value in C++
In this problem, we are given a number n and we have to print all jumping numbers that are smaller than or equal to n.
Jumping Numbers are the number whose adjacent digits differ by one only. Some jumping numbers are 4565, 98, 7. All single-digit numbers are considered as jumping numbers. 235 is not a jumping number.
Now, let’ take an example to understand the problem
Input: N = 32 Output: 0 1 2 3 4 5 6 7 8 9 10 12 21 23 32
To solve this problem, we will assume a graph where 0 is the starting node and traverse it to all reachable nodes. You can traverse it using BFS or DFS. This graph is created using a condition that makes values jumping numbers.
Example
The below code implements our solution −
#include <bits/stdc++.h> using namespace std; void traverse(int N, int num) {    queue<int> q;    q.push(num);    while (!q.empty()) {       num = q.front();       q.pop();       if (num <= N) {          cout << num << " ";          int last_dig = num % 10;          if (last_dig == 0)             q.push((num * 10) + (last_dig + 1));          else if (last_dig == 9)             q.push((num * 10) + (last_dig - 1));          else {             q.push((num * 10) + (last_dig - 1));             q.push((num * 10) + (last_dig + 1));          }       }    } } void printJumpingNumber(int N) {    cout<<0<<" ";    for (int i = 1; i <= 9 && i <= N; i++)    traverse(N, i); } int main() {    int N = 54;    cout<<"Jumping Numbers less than "<<N<<" are :\n";    printJumpingNumber(N);    return 0; }  Output
Jumping Numbers less than 54 are − 0 1 10 12 2 21 23 3 32 34 4 43 45 5 54 6 7 8 9
Advertisements
 