- 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

# 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

- Related Questions & Answers
- Find next greater number with same set of digits in C++
- Find largest number smaller than N with same set of digits in C++
- Largest number less than N with digit sum greater than the digit sum of N in C++
- Find the Next perfect square greater than a given number in C++
- Kth prime number greater than N in C++
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Number of Digits in a^b in C++
- Program to find greater value between a^n and b^n in C++
- Program to find number not greater than n where all digits are non-decreasing in python
- Next higher number with same number of set bits in C++
- Elements greater than the previous and next element in an Array in C++
- Largest even digit number not greater than N in C++
- Number of nodes greater than a given value in n-ary tree in C++
- Python - Consecutive Ranges of K greater than N
- Next greater element in same order as input in C++

Advertisements