《编程之美》有具体分析。
#include <iostream>
#include <cstdio>
using namespace std;
int ones(int n){
int sum = 0;
int factor = 1;
while(n/factor){
int lower = n - (n/factor)*factor;
int curr = (n/factor) % 10;
int higher = n/(factor*10);
if(curr == 0) sum += higher * factor;
else if(curr == 1) sum += higher * factor + lower + 1;
else sum += (higher + 1) * factor;
factor *= 10;
}
return sum;
}
int main(){
int n;
scanf("%d", &n);
printf("%d", ones(n));
return 0;
}