题目要求:
本题要求实现一个统计整数中指定数字的个数的简单函数。
函数接口定义:
int CountDigit( int number, int digit );
其中number是不超过长整型的整数,digit为[0, 9]区间内的整数。函数CountDigit应返回number中digit出现的次数。
裁判测试程序样例:
#include <stdio.h>
int CountDigit( int number, int digit );
int main()
{
int number, digit;
scanf("%d %d", &number, &digit);
printf("Number of digit %d in %d: %d\n", digit, number, CountDigit(number, digit));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
-21252 2
输出样例:
Number of digit 2 in -21252: 3
解答:
int CountDigit( int number, int digit )
{
int n, count = 0;
if (number == digit) /*当number与digit相等时,number一定只有一位数,所以返回1*/
return 1;
if (number < 0) /*当number为负数时,为了方便计算,将其变为正数*/
number = -number;
while (number) /*number不为0就继续循环*/
{
n = number % 10; /*n为number中最后一位数*/
if (digit == n)
count++;
number /= 10; /*将n最后一位数去掉*/
}
return count;
}