题目:1到N中,出现的1的个数
分析:编程之美上面的题,整理一下记录下来
假设1到某个数12x01,设百位上的数字出现1的次数,假设百位上的数字x=0,百位上出现1的情况由100-199,1100-1199,2100-2199
3100-3199,......11100-11199,,总共1200个,当前位的高位为12,有12*100。假设x=1,百位上出现1的次数除了100-199......11100-11199这1200个数外,还有12100-12101这两个数,低位为01,即有百位上出现1的次数为12*100+01+1。当x>1时,百位上出现1的次数为 100-199,1100-1199,......11100-11199,12100-12199 总共1300个数
总结规律
数字 可分为高位high,当前位cur,低位low,当前位倍数因子为factor(例如:百位上 factor=100)
当前位cur为1的次数count=
case cur=0 count=high*factor;
case cur=1 count=high*factor+low+1;
case cur>1 count=(high+1)*factor;
然后计算每一位上出现1的次数即可
代码如下:
#include<stdio.h>
main()
{
int N;
scanf("%d",&N);
int count=0;
int factor=1;
int high=0,low=0;
int cur=0;
while(N/factor!=0)
{
low=N%factor;
cur=(N/factor)%10;
high=N/(factor*10);
switch(cur)
{
case 0:
count+=high*factor;
break;
case 1:
count+=high*factor+low+1;
break;
default:
count+=(high+1)*factor;
break;
}
factor=factor*10;
}
printf("输出:%d",count);
system("pause");
}