本题要求实现一个函数,可统计任一整数中某个位数出现的次数。例如-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; scanf("%d %d", &N, &D);
printf("%d\n", Count_Digit(N, D));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
-21252 2
输出样例:
3
代码长度限制
16 KB
时间限制
400 ms
内存限制int Count_Digit(const int N, const int D) {
int i, a,c, count = 0;
if(N==0&&D==0) return 1; /*当N和D都是0是,应该输出1。毕竟0出现了一次(这个情况属实离谱,贼容易忘,所以单独加上了。)*/
if(N>=0) c =N;
else c =-N;
while (c != 0) {
a = c % 10;
if (a == D) count++;
c = c/ 10; //一个很基本的逐个取出一个数每一位的数字的方法,在很多题都很常见
}
return count;
}