用 C++ 统计位数不同的数字
假设我们有一个非负整数 n。我们需要统计所有与 n 范围内的数字 x 具有唯一位数的数字,其中 x 介于 0 到 10^n 之间。因此,如果 n 为 2,那么结果将是 91,因为我们希望找到从 0 到 100 的且不含 11、22、33、44、55、66、77、88、99 的数字。
为了解决这个问题,我们将按照以下步骤执行 −
如果 n 为 0,则返回 1
n := min(10, n)
如果 n 为 1,则返回 10
ans := 9,ret := 10
对于范围 2 到 n 的 i
ans := ans * (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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP