统计各位数字都不同的数字个数
难度:
标签:
题目描述
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
代码结果
运行时间: 20 ms, 内存: 0.0 MB
// 思路:使用Java Stream来生成所有0到10^n的数字流,
// 过滤出各位不重复的数字并统计数量。
import java.util.stream.IntStream;
public class Solution {
public int countNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
int limit = (int) Math.pow(10, n);
return (int) IntStream.range(0, limit)
.filter(Solution::hasUniqueDigits)
.count();
}
private static boolean hasUniqueDigits(int num) {
boolean[] seen = new boolean[10];
while (num > 0) {
int digit = num % 10;
if (seen[digit]) return false;
seen[digit] = true;
num /= 10;
}
return true;
}
}
解释
方法:
这个题解使用了数学方法来解决问题。对于一个n位数,第一位有9种选择(不能为0),第二位有9种选择,第三位有8种选择,以此类推。所以不同的n位数的个数为9*9*8*...(9-n+2),再加上小于n位数的不同数字的个数,即为最终结果。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在计算不同数字的个数时,第一位数字的选择范围是9而不是10?
▷🦆
在题解中提到'第二位有9种选择',这种说法是否准确?是否应该是10-1=9种选择因为已经选择了一个数字?
▷🦆
对于n=0的情况,为什么输出是1?是否可以解释一下这种特殊情况的逻辑?
▷