PTA6-4 使用函数统计指定数字的个数(C)

本题要求实现一个统计整数中指定数字的个数的简单函数。

函数接口定义:

int CountDigit( int number, int digit );

其中number是不超过长整型的整数,digit为[0, 9]区间内的整数。函数CountDigit应返回number中digit出现的次数。

裁判测试程序样例:

#include <stdio.h>

int CountDigit( int number, int digit );

int main()

{

int number, digit;

复制代码
scanf("%d %d", &number, &digit);
printf("Number of digit %d in %d: %d\n", digit, number, CountDigit(number, digit));

return 0;

}

/* 你的代码将被嵌在这里 */

输入样例:

-21252 2

输出样例:

Number of digit 2 in -21252: 3

c 复制代码
int CountDigit( int number, int digit ){
    if(number==0 && digit==0)
        return 1;
    if(number<0){
        number = ~number+1;
    }
    int count = 0;
    while(number){
        int n = number % 10;
        if(n == digit)
        count++;
        number = number / 10;
    }
    return count;
}
相关推荐
smj2302_7968265212 分钟前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
JANGHIGH14 分钟前
c++ 多线程(二)
开发语言·c++
珑墨27 分钟前
【浏览器】页面加载原理详解
前端·javascript·c++·node.js·edge浏览器
cynicme34 分钟前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5121 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8241 小时前
计数if|
算法
a伊雪2 小时前
c++ 引用参数
c++·算法
程序员Jared2 小时前
深入浅出C语言——程序环境和预处理
c语言
应茶茶2 小时前
从 C 到 C++:详解不定参数的两种实现方式(va_args 与参数包)
c语言·开发语言·c++
Data_agent2 小时前
1688获得1688店铺列表API,python请求示例
开发语言·python·算法