Numbers having Unique (or Distinct) digits

Hello Everyone,

Given a range, print all numbers having unique digits.

Examples :

Input : 10 20 Output : 10 12 13 14 15 16 17 18 19 20 (Except 11) Input : 1 10 Output : 1 2 3 4 5 6 7 8 9 10

Approach:

As the problem is pretty simple, the only thing to be done is :- 1- Find the digits one by one and keep marking visited digits. 2- If all digits occurs one time only then print that number. 3- Else not.

// C++ implementation to find unique digit

// numbers in a range

#include<bits/stdc++.h>

using namespace std;

// Function to print unique digit numbers

// in range from l to r.

void printUnique( int l, int r)

{

// Start traversing the numbers

for ( int i=l ; i<=r ; i++)

{

int num = i;

bool visited[10] = { false };

// Find digits and maintain its hash

while (num)

{

// if a digit occurs more than 1 time

// then break

if (visited[num % 10])

break ;

visited[num%10] = true ;

num = num/10;

}

// num will be 0 only when above loop

// doesn't get break that means the

// number is unique so print it.

if (num == 0)

cout << i << " " ;

}

}

// Driver code

int main()

{

int l = 1, r = 20;

printUnique(l, r);

return 0;

}

Output :

1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20

Another Approach:

Use set STL in order to check if a number has only unique digits. Then we can compare the size of string s formed from a given number and newly created set. For example, let us consider the number 1987, then we can convert the number into the string,

int n;

cin>>n;

string s = to_string(n);

After that, initialize a set with the contents of string s.

  • C++

set< int > uniDigits(s.begin(), s.end());

Then we can compare the size of string s and newly created set uniDigits.

Here is the code for the above approach:

// C++ code for the above approach

#include <bits/stdc++.h>

using namespace std;

// Function to print unique

// numbers

void printUnique( int l, int r){

// Iterate from l to r

for ( int i = l; i <= r; i++) {

// Convert the no. to

// string

string s = to_string(i);

// Convert string to set using stl

set< int > uniDigits(s.begin(), s.end());

// Output if condition satisfies

if (s.size() == uniDigits.size()) {

cout << i << " " ;

}

}

}

// Driver Code

int main()

{

// Input of the lower and

// higher limits

int l = 1, r = 20;

// Function Call

printUnique(l, r);

return 0;

}

Output

1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20