![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Next greater Number than N with the same quantity of digits A and B in C++
Given N, A, and B. Find the number which is greater than N with the same number of A and B digits. Let's see an example.
N = 1234 A = 2 B = 3
We need to check for every possibility of the given number of digits. There are two digits to form the number. And each digit count in the number should be the same.
Algorithm
Initialise A, B, and N.
Write a recursive function.
Check whether the current number is greater than N and has equal number of A and B digits.
Return the number if the above condition satisfies.
- Add the digit A to the result.
- Add the digit B to the result.
- Recursively call the function with the minimum number from the above two.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; long getNextGreaterElement(long result, int A, int A_Count, int B, int B_Count, int N) { if (result > 1e11) { return 1e11; } if (A_Count == B_Count && result >= N) { return result; } return min(getNextGreaterElement(result * 10 + A, A, A_Count + 1, B, B_Count, N), getNextGreaterElement(result * 10 + B, A, A_Count, B, B_Count + 1, N)); } int main() { int N = 1234; int A = 2; int B = 3; cout << getNextGreaterElement(0, A, 0, B, 0, N) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
2233
Advertisements