Skip to content

Commit 6c1c3fb

Browse files
Create Uniquedigits.cpp
1 parent c78c70c commit 6c1c3fb

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Math/Uniquedigits.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
*/
17+
18+
-------------------------------------------------------------------------//C++ code begins here----------------------------------------------------------------------------
19+
20+
21+
class Solution {
22+
public:
23+
int countNumbersWithUniqueDigits(int n) {
24+
if (n == 0) {
25+
return 1;
26+
}
27+
int ans = 10;
28+
int unique_digits = 9;
29+
int available_digits = 9;
30+
while (n-- > 1 && available_digits > 0) {
31+
unique_digits *= available_digits;
32+
ans += unique_digits;
33+
available_digits--;
34+
}
35+
return ans;
36+
}
37+
};

0 commit comments

Comments
 (0)