Algorithm


Problem Name: 357. Count Numbers with Unique Digits

Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

 

Example 1:

Input: n = 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

Example 2:

Input: n = 0
Output: 1

 

Constraints:

  • 0 <= n <= 8

 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if (n<1) {
            return 1;
        }
        
        int nums = 10;
        int base = 9;
        for (int i=2;i < =n && i<= 10; i++) {
            base = base * (9 - i + 2);
            nums += base;
        }
        
        return nums;
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 2

Output

x
+
cmd
91

#2 Code Example with Javascript Programming

Code - Javascript Programming


const countNumbersWithUniqueDigits = function(n) {
  if (n === 0) return 1;
  let res = 10;
  let tmp = 9;
  let remainDigitNum = 9;
  while (n - 1 > 0 && remainDigitNum > 0) {
    tmp = tmp * remainDigitNum;
    res += tmp;
    n -= 1;
    remainDigitNum -= 1;
  }

  return res;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 2

Output

x
+
cmd
91

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def countNumbersWithUniqueDigits(self, n):
        return [1, 10, 91, 739, 5275, 32491, 168571, 712891, 2345851, 5611771, 8877691][n % 11]
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 0

Output

x
+
cmd
1
Advertisements

Demonstration


Previous
#355 Leetcode Design Twitter Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#363 Leetcode Max Sum of Rectangle No Larger Than K Solution in C, C++, Java, JavaScript, Python, C# Leetcode