|
| 1 | +/*Name : Abhinav kumar |
| 2 | +Github username : Abhinavcode13 |
| 3 | +Repository name : data-structures-and-algorithms |
| 4 | +Problem : Count Numbers with Unique Digits in C++ |
| 5 | +Issue Number : #500 |
| 6 | +Problem statement : |
| 7 | +
|
| 8 | +Explanation of the below C++ code : |
| 9 | +
|
| 10 | +In this implementation, we first handle the base case of n = 0 by returning 1. Then, we initialize the answer ans to 10 since there are 10 unique digits between 0 and 9. We also initialize the variables unique_digits and available_digits to 9 since we can't use 0 as the first digit. |
| 11 | +
|
| 12 | +Next, we enter a loop that runs n-1 times (since we have already considered the case of i = 1). In each iteration of the loop, we compute unique_digits as the product of the current value of unique_digits and available_digits. We then add unique_digits to the answer ans and decrement available_digits. This is because we can't use the digits that have already been used for the previous digits. |
| 13 | +
|
| 14 | +Finally, we return the value of ans. |
| 15 | +
|
| 16 | +The time complexity of this algorithm is O(n), where n is the input parameter representing the number of digits. |
| 17 | +
|
| 18 | +The space complexity of this algorithm is O(1), as we are only using a constant amount of extra memory to store the variables ans, unique_digits, and available_digits, regardless of the input size. |
| 19 | +
|
| 20 | +*/ |
| 21 | +-------------------------------------------------------------------------//C++ code begins here---------------------------------------------------------------------------- |
| 22 | + |
| 23 | +class Solution { |
| 24 | +public: |
| 25 | + int countNumbersWithUniqueDigits(int n) { |
| 26 | + if (n == 0) { |
| 27 | + return 1; // return 1 for n = 0 |
| 28 | + } |
| 29 | + int ans = 10; // start with 10 unique digits, as we can have numbers 0-9 |
| 30 | + int unique_digits = 9; // start with 9 digits, as we cannot use 0 as first digit |
| 31 | + int available_digits = 9; // remaining available digits |
| 32 | + while (n-- > 1 && available_digits > 0) { |
| 33 | + unique_digits *= available_digits; // calculate number of unique numbers that can be formed |
| 34 | + ans += unique_digits; // add number of unique numbers to the answer |
| 35 | + available_digits--; // reduce available digits by 1 |
| 36 | + } |
| 37 | + return ans; // return final answer |
| 38 | + } |
| 39 | +}; |
0 commit comments