Count Numbers with Unique Digits in C++


Suppose we have a non-negative integer n. We have to count all numbers with unique digits x, where x is in range 0 to 10^n. So if the number n is 2, then the result will be 91, as we want to find numbers from 0 to 100 without 11, 22, 33, 44, 55, 66, 77, 88, 99.

To solve this, we will follow these steps −

  • if n is 0, then return 1

  • n := min of 10 and n

  • if n is 1, then return 10

  • ans := 9 and ret := 10

  • for i in range 2 to n

    • ans := ans * (9 – i + 2)

    • ret := ret + ans

  • return ret

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int countNumbersWithUniqueDigits(int n) {
      if(n == 0)return 1;
      n = min(10, n);
      if(n == 1)return 10;
      int ans = 9;
      int ret = 10;
      for(int i = 2; i<= n; i++){
         ans *= (9 - i + 2);
         ret += ans;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.countNumbersWithUniqueDigits(3));
}

Input

3

Output

739

Updated on: 02-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements