PTA计数,自己写的超时了

img

img

计算一个数出现了几次,自己用了三个循环,运行超时。改怎么改进,希望有人能指导一下

在while(b!=0)之前,定义一个变量等于b,比如int k = b;然后14行到21行之间的b全部改成k
因为b是for的循环变量,你不能在下面的代码中修改b的值,否则for循环会死循环的啊。

供参考:

#include <stdio.h>
int count(int n, int x) 
{
    int cnt = 0, k;
    for (int i = 1; k = n / i; i *= 10) 
    {
        int high = k / 10;
        if (x == 0) {
            if (high) 
                high--;
            else
                break;
        }
        cnt += high * i;
        int cur = k % 10;
        if (cur > x)
            cnt += i;
        else if (cur == x)
            cnt += n - k * i + 1;
    }
    return cnt;
}
int main()
{
    int t, n, x;
    scanf("%d", &t);
    while (t--) {
        scanf("%d %d", &n, &x);
        printf("%d\n", count(n, x));
    }
    return 0;
}