Leetcode 357. Count Numbers with Unique Digits
Given a non-negative integer n
, count all numbers with unique digits, x, where 0 <= x < 10^n
.
n
we should consider?
0 <= n <= 10
.n >= 1
.n = 0
, there is only one number (0).n = 1
, there are 10 numbers (0 through 9), all of which are unique.n = 2
, we need to count numbers from 0 to 99 with unique digits.
n
, we generalize using permutation principles:
n
.#include <iostream>
int countNumbersWithUniqueDigits(int n) {
if (n == 0) {
return 1;
}
int unique_count = 10; // For n = 1, 0 to 9.
int available_digits = 9; // Digits left to use for each new place
int current_count = 9; // Remaining unique numbers to place for each position
int max_digits = std::min(n, 10); // Since 10! has only 10 digits.
for (int i = 2; i <= max_digits; ++i) {
current_count *= available_digits;
unique_count += current_count;
--available_digits;
}
return unique_count;
}
int main() {
int n = 2; // Example input
int result = countNumbersWithUniqueDigits(n);
std::cout << "Count of numbers with unique digits for n = " << n << " is: " << result << std::endl;
return 0;
}
n
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?