计数问题

    技术2022-05-19  23

    问题陈述:

     

    http://acm.hrbeu.edu.cn/index.php?act=problem&id=1001&cid=17

    给你两个数a和b,你的任务是计算出1在a和b之间出现的次数,比如说,如果a=1024,b=1032,那么a和b之间的数就是:

    1024 1025 1026 1027 1028 1029 1030 1031 1032

    则有10个1出现在这些数中。

    简单的实现思路:


    #include <stdio.h>#include <stdlib.h>

    int CountDigists(int n){    int count = 0;    while(n > 0)    {        if(n  % 10 == 1)        {            count++;        }        n = n / 10;    }

        return count;}

    int CountRangeDigists(int a, int b){    int ret =  0;    int i = 0;    for(i = a; i <= b; ++i)    {        ret += CountDigists(i);    }

        return ret;}

    int main(){    int a[500], b[500];

        int i = 0;    // get the intput    while((scanf("%d %d", &a[i], &b[i]) == 2) &&          (a[i] !=0 ) &&          (b[i] != 0))          {              ++i;          }

        // ooutput the result    int j = 0;    for( ; j <= (i - 1); ++j)    {        printf("%d/n", CountRangeDigists(a[j], b[j]));    }

        return 0;}

     


     

    上面仅仅是最简单的实现方法,更为直接的方式是通过计算得到计算公式,个人认为比较麻烦。再次略去。

     


    最新回复(0)