首页 > 代码库 > 给定正整数N,统计1-N的连续整数中1的个数

给定正整数N,统计1-N的连续整数中1的个数

int CountNumOf1(int digital)
{
int num = 0;
while(digital)
{
num += (digital % 10 == 1) ? 1: 0;
digital /= 10;
}
return num;
}
int CountTotalNumOf1(int N)
{
int sum=0;
printf("前N个连续数是:\n");
for(int i=1;i<=N;++i)
{
printf("%d ",i);
sum += CountNumOf1(i);
}
return sum;
}
int main(void)
{
int n;
scanf("%d",&n);
printf("\n1的个数为:%2d\n",CountTotalNumOf1(n));
return 0;
}


本文出自 “sunnyting” 博客,转载请与作者联系!

给定正整数N,统计1-N的连续整数中1的个数