题目描述
试计算在区间 11 到 nn的所有整数中,数字x(0 ≤ x ≤ 9)x(0≤x≤9)共出现了多少次?例如,在 11到1111中,即在 1,2,3,4,5,6,7,8,9,10,111,2,3,4,5,6,7,8,9,10,11 中,数字 11 出现了 44 次。
输入格式
22个整数n,xn,x,之间用一个空格隔开。
输出格式
11个整数,表示xx出现的次数。
输入输出样例
输入
11 1
输出
4
思路:本来我想用字符串来做的,后来发现洛谷上不认识这个itoa函数,所以就用了普通的拆数法来写。就是利用对10整除和取余,不断剥离每一个值,再判断是否和数字x一致
#include<iostream>
using namespace std;
int main() {
int n, x;
cin >> n >> x;
int t, count = 0;
for (int i = 1; i <= n; i++) {
t = i;
while (1) {
if (t == 0) {
break;
}
if (t % 10 == x) {
count++;
}
t = t / 10;
}
}
cout << count;
}
ps:还是附上另外一种解法吧,在vs上写的
#include<iostream>
#include<cstring>
using namespace std;
int f(char n[], char x) {
int count = 0;
for (int i = 0; i < 10; i++) {
if (n[i] == x) {
count++;
}
}
return count;
}
int main() {
int n;
char x, temp[10];
int sum = 0;
cin >> n >> x;
for (int i = 1; i <= n; i++) {
sum += f(_itoa(i, temp, 10), char(x));
}
cout << sum;
}