In this Leetcode Count Numbers with Unique Digits problem solution you have given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

Leetcode Count Numbers with Unique Digits problem solution


Problem solution in Python.

class Solution:
    def countNumbersWithUniqueDigits(self, n):
        if n == 0:
            return 1
        
        if n == 1:
            return 10
        
        if n == 2:
            return 91
        
        i = 3
        total = 91
        k = 9*9
        
        while i <= n:
            total += k * (11 - i)
            k *= (11 - i)
            i += 1
            
            if i == 11:
                break
        
        return total



Problem solution in Java.

class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if(n==0){
            return 1;
        }
        int sum = 0;
        for(int k=1;k<=n;k++){
            sum += count(k);
        }
        return sum+1;
    }
    
    public int count(int n){
        int product = 9;        
        for(int i=0;i<n-1;i++){
            product = product * (9-i);
        }
        return product;
    }
}


Problem solution in C++.

int countNumbersWithUniqueDigits(int n) {
        int s = 0;
        int p = 1;
        for (int i=1; i<=min(10, n); i++) {
            s += p;
            p *= 10 - i;
        }
        return s * 9 + 1;
    }


Problem solution in C.

int fac(int a, int b){
    int result = 1;
    while(a > b){
        result *= a;
        a--;
    }
    return result;
}
int countNumbersWithUniqueDigits(int n) {
    if(n == 1 || n == 0) return pow(10, n);
    if(n > 10) return countNumbersWithUniqueDigits(10);
    
    int result = 0;
    result = countNumbersWithUniqueDigits(n - 1) + fac(9, 9-n) + fac(9, 9 - n + 1) * (n - 1);
    return result;
}