C编程:数组编程实例分享

描述

C编程笔试 — 数组编程问题 

    题目要求

      试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9) 共出现了多少次?例如,在 1 到 11 中,即在 1,2,3,4,5,6,7,8,9,10,11 中,数字 1 出现了 4 次。

 输入示例:

输入:
11
输出:
4
 说明: 在 1 到 11 中,即在 1,2,3,4,5,6,7,8,9,10,11 中,数字 1 出现了 4 次。

 示例代码:

#include 
#include 

int solution(int m, int n){
    int result;

    // TODO: 请在此编写代码
    int i=0,j=0;
    int data=m;
    int cnt=0;
	if(n>m)return 0;
    result=1;
    while(data)
    {
      data/=10;
      cnt++;//计算m是几位数
    }
    for(i=10;i<=m;i++)//11
    {
      data=1;
      for(j=1;j<=cnt;j++)
      {
          if(i/data%10 == n)result++;
          data*=10;
      }
    }

    return result;
}
int main() {

    int m;
	int n;
	printf("请输入整数m:");
    scanf("%d", &m);
	printf("请输入要查找的数0~9:");
	scanf("%d", &n);
	struct timeval tv;
	gettimeofday(&tv, NULL);//获取系统精准时间
    int result = solution(m, n);
    printf("1~%d中%d出现的次数:%d\n", m,n,result);
	struct timeval tv2;
	gettimeofday(&tv2, NULL);//获取系统精准时间
	printf("程序运行时间:%ld s--%ld us\n",tv2.tv_sec-tv.tv_sec,tv2.tv_usec-tv.tv_usec);
    return 0;
}

 测试结果:

C语言

 

 

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分