从个位开始分别算出从1到n这个位有多少的1
如果这位大于1,那么1的总数等于(左边的值+1)*(右边的位数)
如果这位等于1,那么1的总数等于(左边的值)*(右边的位数)+右边的值
如果这位等于0,那么1的总数等于(左边的值)*(右边的位数)
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
int c,base;
int main(){
int n;
scanf("%d",&n);
c=0;base=1;
while(n/base!=0){
int low=n%base;
int now=(n/base)%10;
int high=n/(base*10);
if(now==0)
c+=high*base;
else if(now==1)
c+=high*base+low+1;
else
c+=(high+1)*base;
base*=10;
}
printf("%d\n",c);
return 0;
}
本文介绍了一种计算从1到任意数N中数字1出现总次数的方法。通过将N分解为高位、当前位和低位三部分,并根据不同情况计算1的出现次数,实现了高效的求解算法。
2064

被折叠的 条评论
为什么被折叠?



