

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
- Related Questions & Answers
- Count numbers (smaller than or equal to N) with given digit sum in C++
- Print all prime numbers less than or equal to N in C++
- Print all Semi-Prime Numbers less than or equal to N in C++
- Euler’s Totient function for all numbers smaller than or equal to n in java
- Mask array elements greater than or equal to a given value in Numpy
- Find all factorial numbers less than or equal to n in C++
- Minimum numbers which is smaller than or equal to N and with sum S in C++
- Count elements smaller than or equal to x in a sorted matrix in C++
- Mask an array where less than or equal to a given value in Numpy
- Largest number smaller than or equal to N divisible by K in C++
- An interesting solution to get all prime numbers smaller than n?
- How to find numbers in an array that are greater than, less than, or equal to a value in java?
- Count elements less than or equal to a given value in a sorted rotated array in C++
- Delete all the nodes from a doubly linked list that are smaller than a given value in C++
- Check which element in a masked array is greater than or equal to a given value in NumPy
Advertisements