目录
题目
给定两个正整数 n 和 k,求从 1 到 n 这 n 个正整数的十进制表示中 k 出现的次数。
输入格式
共一行,包含两个整数 n 和 k。
输出格式
输出一个整数,表示答案。
数据范围
1≤n≤10^6
1≤k≤9
样例
题解
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int res = 0;
for (int i = 1; i <= n; i ++ )
for (auto c: to_string(i))
if (c - '0' == k)
res ++ ;
cout << res << endl;
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
typedef long long ll;
using namespace std;
int main()
{
ll a, b,ans=0; cin >> a >> b;
for (int i = 1; i <= a; i++)
for (auto c : to_string(i))
if (c == b + '0')ans++;
cout << ans;
}
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int res = 0;
for (int i = 1; i <= n; i ++ )
for (int j = i; j; j /= 10)
if (j % 10 == k)
res ++ ;
cout << res << endl;
return 0;
}
注意事项
1.字符可以通过-‘0’转成数字,数字可通过+‘0’转成字符。
2.to_string用法:
3.for(auto a:b)循环: