用C ++计数唯一数字
假设我们有一个非负整数n。我们必须计算具有唯一数字x的所有数字,其中x的范围是0到10^n。因此,如果数字n为2,则结果将为91,因为我们要查找从0到100的数字,而没有11、22、33、44、55、66、77、88、99。
为了解决这个问题,我们将遵循以下步骤-
如果n为0,则返回1
n:=10和n中的最小值
如果n为1,则返回10
ans:=9并ret:=10
对于我2到n
回答:=回答*(9–i+2)
ret:=ret+ans
返回ret
例子(C++)
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if(n == 0)return 1;
n = min(10, n);
if(n == 1)return 10;
int ans = 9;
int ret = 10;
for(int i = 2; i<= n; i++){
ans *= (9 - i + 2);
ret += ans;
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.countNumbersWithUniqueDigits(3));
}输入值
3
输出结果
739