6-9 统计个位数字

40 阅读1分钟

本题要求实现一个函数,可统计任一整数中某个位数出现的次数。例如-21252中,2出现了3次,则该函数应该返回3。

函数接口定义:

int Count_Digit ( const int N, const int D );

其中ND都是用户传入的参数。N的值不超过int的范围;D是[0, 9]区间内的个位数。函数须返回ND出现的次数。

pintia.cn/problem-set…

解答

int Count_Digit ( const int N, const int D )
{
    int n = N;
    // 去掉负号
    if (n < 0)    n *= -1;

    int counter = 0;
    // 用do while,确保不遗漏N, D都为0的情况
    do {
        // 从个位开始统计次数
        if (n % 10 == D)    ++counter;

        n /= 10;
    } while(n);

    return counter;
}