[Leetcode] Count Numbers with Unique Digit

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


public class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if(n == 0){
            return 1;
        }
        int result = 0;
        for(int i = 1; i <= n; i++) {
            result += uniqueNumberWithLength(i);
        }
        return result;
    }
    
    private int uniqueNumberWithLength(int k) {
        if(k == 1) {
            return 10;
        }
        int result = 9;
        int factor = 9;
        for(int i = 1; i < k && factor >= 0; i++) {
            result *= factor;
            factor--;
        }
        return result;
    }
}


你可能感兴趣的:(leetcode)