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

本文介绍了一个算法,用于统计任意整数中特定位数的出现次数,包括处理负数和特殊情况如当指定位数为0且整数也为0的情况。通过实例演示了如何实现这一功能,并提供了完整的源代码。

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

/*

函数接口定义:

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

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

*/


#include <stdio.h>



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


int main()
{
    int N, D;

    while (scanf("%d %d", &N, &D) != EOF){
     printf("%d\n", Count_Digit(N, D));
}
    return 0;
}


int Count_Digit ( const int N, const int D )
{
int tmp[10] = {0};
int n = N;
if (n < 0)
{
n = -n;
}
if ((n == 0) && (D == 0))
{
return 1;
}
while (n > 0)
{
for (int i = 0; i < 10; i++)
{
if (n % 10 == i)
{
tmp[i] += 1; 
}
}
n = n / 10; 
  }
for (int i = 0; i < 10; i++)
{
if (D == i)
{
return tmp[i];
}
}
return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值