/*可统计任一整数中某个位数出现的次数。例如-21252中,2出现了3次,则该函数应该返回3。 */
/*
函数接口定义:
int Count_Digit ( const int N, const int D );
其中N和D都是用户传入的参数。N的值不超过int的范围;D是[0,
9]区间内的个位数。函数须返回N中D出现的次数。
*/
#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;
}
本文介绍了一个算法,用于统计任意整数中特定位数的出现次数,包括处理负数和特殊情况如当指定位数为0且整数也为0的情况。通过实例演示了如何实现这一功能,并提供了完整的源代码。
1159

被折叠的 条评论
为什么被折叠?



