# 文章标题

1. dp[n][0] = dp[n-1][0] + 8*dp[n-1][0] = dp[n-1][0] * 9.

2. dp[n][i] = dp[n-1][i] + dp[n-1][i-1] + 8*dp[n-1][i]

``````for(int c = len-1; c>=1; --c) {
cnt += dp[len-1][c]*c;
}``````

zhzz至于第一部分, 因为必须<=n, 所以我们需要逐一位处理:

``````5314
4xxx
3xxx
2xxx
1xxx

``````5314
52xx
51xx
50xx

``````int countDigitOne(int n) {
if(0 == n) {
return 0;
}
int len = 1;
++len;
}

vector<vector<int>> dp(len+1, vector<int>(len+1, 0));
dp[0][0] = 1;
dp[1][0] = 9;
dp[1][1] = 1;
for(int l = 2; l <= len; ++l) {
dp[l][0] = dp[l-1][0] * 9;
for(int c = 1; c <= l; ++c) {
dp[l][c] = dp[l-1][c] * 9 + dp[l-1][c-1];
}
}

int cnt = 0;
/*size = len*/
int prev_1_cnt = 0;
for(int i = len; i >= 1; --i) {
if(i == len) {
}else if(digit == 1){
}else {
}
for(int l = 0; l <= i-1; ++l) {
cnt += not1_head * dp[i-1][l] * (prev_1_cnt+l);
}
}
if(digit > 1) {
for(int c = 0; c <= i-1; ++c) {
cnt += dp[i-1][c] * (prev_1_cnt + c +1);
}
}

if(digit == 1) {
++prev_1_cnt;
}
}
/*size < len*/
for(int c = len-1; c>=1; --c) {
cnt += dp[len-1][c]*c;
}

cnt += prev_1_cnt;
return cnt;
}
``````

a前面的方法还是非常繁琐的. 这里再引入StefanPochmann 大神的解法

a我们只分析百位上的情况:
n=3141592

``````3141592
0-3141|1|0-99

n=3141192

``````3141192
0-3140|1|0-99
3141|1|0-91

``````3141092
0-3140|1|0-99

``````int countDigitOne(int n) {
if(0 == n) {
return 0;
}
int cnt = 0;
const int a = n / mask;
const int b = n % mask;
const int v = a%10;
if(v > 1) {
cnt += (a/10 + 1) * mask;
}else if(v == 1) {
cnt += (a/10) * mask + b+1;
}else {