
- 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
Find next greater number with same set of digits in C++
In this problem, we are given an element N. We need to find the next greater number with the same set of digits. We need to find the smallest number with the same digit which is greater than N.
Let’s take an example to understand the problem,
Input
N = "92534"
Output
92543
Solution Approach
A simple solution to the problem to find the next greater element is by the following approach −
Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element.
After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number.
Then sort the remaining subarray and return the output.
Program to illustrate the working of our solution,
Example
#include <iostream> #include <cstring> #include <algorithm> using namespace std; void findNextGreater(char number[], int n) { int i, j; for (i = n-1; i > 0; i--) if (number[i] > number[i-1]) break; if (i==0) { cout<<"Next number is not possible"; return; } int x = number[i-1], smallest = i; for (j = i+1; j < n; j++) if (number[j] > x && number[j] < number[smallest]) smallest = j; char temp = number[smallest]; number[smallest] = number[i-1]; number[i-1] = temp; sort(number + i, number + n); cout<<number; return; } int main(){ char number[] = "92534"; int n = strlen(number); cout<<"The next number with same set of digits is "; findNextGreater(number, n); return 0; }
Output
The next number with same set of digits is 92543
- Related Questions & Answers
- Next greater Number than N with the same quantity of digits A and B in C++
- Next higher number with same number of set bits in C++
- Find largest number smaller than N with same set of digits in C++
- Next greater integer having one more number of set bits in C++
- Find next Smaller of next Greater in an array in C++
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Next greater element in same order as input in C++
- Find the Next perfect square greater than a given number in C++
- Next Greater Element in C++
- Find smallest number with given number of digits and sum of digits in C++
- Find the Largest number with given number of digits and sum of digits in C++
- Next Greater Element II in C++
- Next Greater Element III in C++
- Find Next Sparse Number in C++
- Maximum number of contiguous array elements with same number of set bits in C++
Advertisements