Print all numbers less than N with at-most 2 unique digits in C++


In this problem, we are given an integer N and we have printed all the number less than N with at-most 2 unique digits i.e. maximum 2 different digits can be used to create the number.

Let’s take an example to understand the problem −

Input: N = 17
Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

To solve this problem, we will be generating all numbers that have only two unique digits. Our number generating process starts from 0 and ends when our number is equal to or greater than N. For two unique chosen, recursively generate numbers using num*10+i and num*10+j. There may arise some duplicate numbers in this process. So, we can use set to store numbers to avoid it.

Example

This program shows the implementation of our approach to solve the problem

 Live Demo

#include <bits/stdc++.h>
using namespace std;
set<int> numbers;
void generateNumbers(int n, int num, int i, int j){
   if (num > 0 && num < n)
      numbers.insert(num);
   if (num >= n)
      return;
   if (num*10+i > num)
      generateNumbers(n, num*10+i, i, j);
   generateNumbers(n, num*10+j, i, j);
}
void printUniqueBitNumber(int n){
   for (int i = 0; i <= 9; i++)
      for (int j = i + 1; j <= 9; j++)
         generateNumbers(n, 0, i, j);
   cout<<"The numbers are generated are : ";
   while (!numbers.empty()) {
      cout<<*numbers.begin()<<" ";
      numbers.erase(numbers.begin());
   }
}
int main(){
   int n = 17;
   printUniqueBitNumber(n);
   return 0;
}

Output

The numbers are generated are : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Updated on: 22-Jan-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements