C语言 计算1到N中数字1出现的个数

如题所述

算法分析:

1. å®šä¹‰N 及用来统计的cnt, 用来循环的n;

2. 输入N ;

3. 将n从1到N循环, 对于每个n执行如下操作:

a) 循环取出n的每位数字值

b)判断该位是否为1, 如是则累加到cnt上。 

4. 输出结果。 

代码如下:

#include <stdio.h>
int main()
{
int n, N, cnt = 0;
scanf("%d",&N);//输入N值。
for(n = 1;n<=N; n ++)//循环执行
{
int t = n;
while(t)//循环取出每一位。
{
if(t%10 == 1) cnt++;
t/=10;
}
}
printf("%d\n", cnt);//输出结果
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-05-08
#include <stdio.h>

int main() {
int i,N,t,cnt;
while(scanf("%d",&N) == 1) {
cnt = 0;
for(i = 1; i <= N; ++i) {
t = i;
while(t) {
if(t % 10 == 1) ++cnt;
t /= 10;
}
}
printf("cnt = %d\n",cnt);
}
return 0;
}

本回答被提问者采纳
第2个回答  2021-05-03
从最高位到个个位处理,如32102的千位上是2,那么万位会出现10000个1 { 万位取1,0到9999 } 千位上会出现4000 { 3000(万位是0到2,千位取1) + 1000(万位是0,千位是1,000到102)} 个1 ,百位上会出现3203个1
#include <math.h>
#include <stdio.h>
int main()
{
int n;
scanf ("%d", &n);
int len = (int)(log10(n));
int a, b, c, ans = 0;
int now;
while (len != -1 )
{
now = 0;
a = pow(10, (double)(len + 1));
b = pow(10, (double)len);
c = (n % a) / b;
if (c == 1)
now += n % b + 1;
if (c > 1)
now += b;
now += n / a * b;
ans += now;
printf ("%d %d\n", len, now);
len -- ;
}
printf ("%d", ans);
return 0;
}
第3个回答  2014-05-08
真无聊的编程题!

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网