本题要求实现一个函数,可统计任一整数中某个位数出现的次数。例如-21252中,2出现了3次,则该函数应该返回3。
函数接口定义:
int Count_Digit ( const int N, const int D );
其中N和D都是用户传入的参数。N的值不超过int的范围;D是[0, 9]区间内的个位数。函数须返回N中D出现的次数。
解题思路:通过对10取余,和除以10。可以获取数字N的每一位数字,每一位数字都跟D进行比较。
int Count_Digit ( const int N, const int D )
{
//处理一些边界情况
int M = N;
if ( M < 0 ){
M = -M;
}else if ( M == 0 ){
if ( D == 0 ){
return 1;
}else{
return 0;
}
}
//用count来记录数字D出现的次数
int count = 0;
while ( M > 0 ){
if ( M%10 == D ){
count++;
}
M /= 10;
}
return count;
}