AdSense

Monday, June 13, 2016

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])

The trick of this problem is to find the pattern of how to find numbers with unique numbers. The code looks rather easy, but very confusing.

i = 1, 10: nothing is dupliated
i = 2, 9 * 9: the first digit has 9 options (exclude 0), the second digit also has 9 options (exclude the number already taken by the first digit, but include 0).
i = 3, 9 * 9 * 8: first two digits follows rules in i = 2, then the third digit has options that exclude all numbers taken by the previous two digits.
.
.
.
i     , 9 * 9 * 8 *... * (10 - i + 1),  the last digit has options that exclude those already chosen by all previous digits.

The final result is the sum of all results.

public int countNumbersWithUniqueDigits(int n) {
        if (n == 0)
            return 1;
        int rst = 10, count = 9;
        for (int i = 2; i <= n; i++) {
            count *= (10 - i + 1);
            rst += count;
        }
        return rst;
    }


No comments:

Post a Comment