题解 | 记数问题

记数问题

https://www.nowcoder.com/practice/28b2d9f2bf2c48de94a1297ed90e1732

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

// int main() {
//     int n,x;
//     scanf("%d %d",&n,&x);
//     int *arr = (int *)malloc(n * sizeof(int));
//     for(int i=0;i<n;i++){
//         arr[i]=i+1;
//     }
//     int N=0;
//     for(int j=0;j<n;j++){
//         int temp=arr[j];
//         while(temp>0){
//         if(temp%10==x){
//             N+=1;
//         }
//         temp=temp/10;
//     }
//     }
//     printf("%d\n",N);
//     return 0;
// }
//不用数组实现
#include <stdio.h>

int main() {
    int n, x;
    scanf("%d %d", &n, &x);
    
    // 用专门的变量统计次数,初始化为0
    int count = 0;
    
    // 直接遍历1~n,无需数组
    for (int num = 1; num <= n; num++) {
        int temp = num;
        while (temp > 0) {
            if (temp % 10 == x) {
                count++;
            }
            temp /= 10;
        }
    }
    
    printf("%d\n", count);
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务