357. 计算各个位数不同的数字个数
给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10n 。
示例:
输入: 2
输出: 91
解释: 答案应为除去 11,22,33,44,55,66,77,88,99 外,在 [0,100) 区间内的所有数字。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-numbers-with-unique-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner;
class Solution {
public int countNumbersWithUniqueDigits(int n) {
// 9 * 8 * 7 * 6 * 5
// 9 * 8 * 7 * 6
// 9 * 8 * 7
// 9 * 8
// 9
if (n <= 0) {
return 1;
}
int start = 9, end = Math.max(9 - n + 1, 1);
/**
* 第一个数可以是1~9
*/
int base = 9;
int ans = 9;
/**
* 第二个数可以是剩余9个数中的一个
* 第三个数可以是剩余8个数中的一个
*/
for (int i = start; i > end; --i) {
base *= i;
ans += base;
}
/**
* 加上0
*/
return ans + 1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(new Solution().countNumbersWithUniqueDigits(in.nextInt()));
}
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号