统计给定范围内数字2出现的次数 - C++ 代码实现
本文提供 C++ 代码实现,用于统计给定范围内所有整数中数字 2 出现的次数。
问题描述
请统计某个给定范围[L, R]的所有整数中,数字 2 出现的次数。
比如给定范围[2, 22],数字 2 在数 2 中出现了 1 次,在数 12 中出现 1 次,在数 20 中出现 1 次,在数 21 中出现 1 次,在数 22 中出现 2 次,所以数字 2 在该范围内一共出现了 6 次。
输入
输入共 1 行,为两个正整数 L 和 R,之间用一个空格隔开。
输出
输出共 1 行,表示数字 2 出现的次数。
C++ 代码实现
#include <iostream>
using namespace std;
int countDigit2(int n) {
int count = 0;
while (n > 0) {
if (n % 10 == 2) {
count++;
}
n /= 10;
}
return count;
}
int countRangeDigit2(int L, int R) {
int count = 0;
for (int i = L; i <= R; i++) {
count += countDigit2(i);
}
return count;
}
int main() {
int L, R;
cin >> L >> R;
int count = countRangeDigit2(L, R);
cout << count << endl;
return 0;
}
该代码使用两个函数实现,countDigit2 函数用于统计一个整数中数字 2 出现的次数,countRangeDigit2 函数用于统计指定范围内所有整数中数字 2 出现的次数。
在 countDigit2 函数中,使用循环遍历整数的每一位,如果某一位的数字为 2,则计数器加 1,然后将整数除以 10,继续处理下一位。
在 countRangeDigit2 函数中,使用循环遍历指定范围内的所有整数,对每个整数调用 countDigit2 函数得到数字 2 出现的次数,并累加到计数器中。
最后,在 main 函数中,从输入中读取范围的起始和结束值,调用 countRangeDigit2 函数得到结果,并输出。
原文地址: https://www.cveoy.top/t/topic/pLnu 著作权归作者所有。请勿转载和采集!