C++统计2的个数
作者:野牛程序员:2023-03-30 13:52:14C++程序设计阅读 3180
【详细描述】 请统计某个给定范围[L, R]的所有整数中,数字2出现的次数。 比如在给定范围[2, 22],数字2在数2中出现了1次,在数12中出现了1次,在数20中出现了1次,在数21中出现了1次,在数22中出现了2次,所以数字2在该范围内一共出现了6次。 输入: 输入共一行,为两个正整数L和R,之间用一个空格隔开。 输出:输出共1行,表示数字2出现的次数。 【样例输入】 2 22 【样例输出】 6
方法一:
#include <iostream>
using namespace std;
int main() {
int L, R, count = 0;
cin >> L >> R;
for (int i = L; i <= R; i++) {
int n = i;
while (n > 0) {
if (n % 10 == 2) { // 判断个位是否为2
count++;
}
n /= 10; // 去掉个位
}
}
cout << count << endl;
return 0;
}方法二:调用自定义函数
#include <iostream>
using namespace std;
int countDigitTwo(int n) {
int count = 0;
while (n > 0) {
if (n % 10 == 2) { // 判断个位是否为2
count++;
}
n /= 10; // 去掉个位
}
return count;
}
int main() {
int L, R, count = 0;
cin >> L >> R;
for (int i = L; i <= R; i++) {
count += countDigitTwo(i);
}
cout << count << endl;
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

