统计数字出现次数-枚举法

要求:计算数字k在0到n中的出现的次数,k可能是0~9的一个值。

样例

例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)

static void StaticNum(int num, int search)
{
    int temp = 0;
    int test = 0;
    int count = 0;
    for (int i = 0; i <= num; i++)
    {
        temp = i;
        do
        {
            test = temp % 10;
            temp = temp / 10;

            if (test == search)
                count++;

        } while (temp != 0);
    }

    Console.WriteLine("0到" + num + "数字" + search + "出现了" + count + "次");
}

首页 我的博客
粤ICP备17103704号