请统计某个给定范围[L, R]的所有整数中,数字2出现的次数请统计某个给定范围[L, R]的所有整数中,数字2出现的次数。
比如给定范围[2, 22],数字2
请统计某个给定范围[L, R]的所有整数中,数字2出现的次数请统计某个给定范围[L, R]的所有整数中,数字2出现的次数。
比如给定范围[2, 22],数字2
关注【以下回答由 GPT 生成】
#include <stdio.h>
int countDigit2(int L, int R) {
int count = 0;
for (int i = L; i <= R; i++) {
int n = i;
while (n > 0) {
if (n % 10 == 2) {
count++;
}
n /= 10;
}
}
return count;
}
int main() {
int L = 2;
int R = 22;
int result = countDigit2(L, R);
printf("The number of times 2 appears in the range [%d, %d] is %d\n", L, R, result);
return 0;
}
这个程序使用了循环来遍历给定范围内的每一个整数,然后对每一个整数进行除以10的取余操作,以判断该数字中是否包含数字2。统计出现次数后返回结果。
【相关推荐】