Count Numbers with Unique Digits

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

Example:

Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])

Credits:Special thanks to @memoryless for adding this problem and creating all test cases.

Solution

public class Solution {
     public int countNumbersWithUniqueDigits(int n) {
                 if (n == 0) return 1;

        if (n == 1) return 10;

        int result = 0;
        for(int i = n; i >= 1; i --) {
            result += countNumbersWithUniqueDigitsHelper(i);
        }

        return result;

    }

    private int countNumbersWithUniqueDigitsHelper(int n) {
        if (n == 1) return 10;

        int result = 9;
        int current = 9;
        for(int i = n -1; i > 0; i --) {
            if (current == 0) {
                break;
            }

            result *= current;
            current --;
        }

        return result;
    }
}

results matching ""

    No results matching ""