Use two methods to solve the "count the number of numbers with different digits" problem

9. Count the number of numbers with different numbers

9.1. Requirements for the title

​ Given an integer n, count and return the number of numbers x with different digits, where 0 <= x < 10n.

示例 1:
输入:n = 2
输出:91
解释:答案应为除去 11、22、33、44、55、66、77、88、99 外,在 0 ≤ x < 100 范围内的所有数字。 

示例 2:
输入:n = 0
输出:1

提示:
0 <= n <= 8

Source: LeetCode
Link: https://leetcode-cn.com/problems/count-numbers-with-unique-digits

9.2, problem-solving ideas

the first method:

When n=0, the value is only one, which is not equal;
when n=1, the value is [0,9], and the 10-digit numbers are not equal;
when n>1, there is a formula Please add image description, which can be calculated according to the formula calculate.

The second method:

Use the hit meter directly.

9.3. Algorithms

the first method

class Solution {
    
    
    public int countNumbersWithUniqueDigits(int n) {
    
    
        //n=0
        if(n == 0){
    
    
            return 1;
        }
        //n=1
        if(n == 1){
    
    
            return 10;
        }
        //n>1
        int count = 9,ans = 10,a = 9;
        while(n > 1 && count > 0){
    
    
            a *= count;
            ans += a;
            count--;
            n--;
        }
        return ans;
    }
}

The second method

class Solution {
    
    
    public int countNumbersWithUniqueDigits(int n) {
    
    
        int [] array = {
    
    1,10,91,739,5275,32491,168571,712891,2345851};
        return array[n];
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124109005