题号:NC16538
时间限制:C/C++/Rust/Pascal 1秒,其他语言2秒
空间限制:C/C++/Rust/Pascal 128 M,其他语言256 M
64bit IO Format: %lld
题目描述
试计算在区间1 到n 的所有整数中,数字x(0 ≤ x ≤ 9)共出现了多少次?
例如,在1到11 中,即在1、2、3、4、5、6、7、8、9、10、11 中,数字1 出现了4 次。
输入描述:
输入共1行,包含2个整数n、x,之间用一个空格隔开。
输出描述:
输出共1行,包含一个整数,表示x出现的次数。
示例1
输入
复制11 1
11 1
输出
复制4
4
备注:
对于100%的数据,1≤ n ≤ 1,000,000,0 ≤ x ≤ 9。
方法一:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,x;
cin>>n>>x;
int count=0;
for(int i=1;i<=n;i++){
int tmp=i;
while(tmp>0){
int a=tmp%10;
if(a==x){
count++;
}
tmp/=10;
}
}
cout<<count;
return 0;
}
方法二:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,x;
cin>>n>>x;
int count=0;
for(int i=1;i<=n;i++){
string s=to_string(i);
for(int j=0;j<s.size();j++){
if(s[j]-'0'==x){
count++;
}
}
}
cout<<count;
return 0;
}