Tuesday, September 25, 2018

Leetcode 357. Count Numbers with Unique Digits

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Input: 2
Output: 91 
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, 
             excluding 11,22,33,44,55,66,77,88,99


Code (Java):
class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if (n >= 11) {
            return 0;
        }
        
        int ans = 1;
        
        for (int i = 1; i <= n; i++) {
            int factor = 9;
            int num = 9;
            for (int j = 2; j <= i; j++) {
                num *= factor;
                factor--;
            }
            ans += num;
        }
        
        return ans;
    }
}

Note:
1. The most significant bit can't be 0, so it  can only be 1 to 9, so the second bit has 9 possible digits.

2. n can be at most 10. If n is greater than 10, the result will be 0. That's because of the pigeonhole theory. 

No comments:

Post a Comment