P1980 [NOIP2013 普及组] 计数问题
打卡2
题目描述:试计算在区间 1到 n的所有整数中,数字x(0 ≤ x ≤ 9)x(0≤x≤9)共出现了多少次?例如,在 1到11中,即在 1,2,3,4,5,6,7,8,9,10,111,2,3,4,5,6,7,8,9,10,11 中,数字 1 出现了 4 次。
这道题有两种方法来解。第一种,是直接来用求余符号算出数字的每一位是否和y相等,如果相等,count+1;如果不相等继续除以10,求余,直到j=0为止。应该注意的是,i赋值给j操作要在while循环外,否则j每次计算下一位,都会被重新赋值。
#include<bits/stdc++.h>
using namespace std;
int main(){
int x,y;
cin>>x>>y;
int i,j,k,count=0;
for(i=1;i<=x;i++){
j=i;
while(j!=0){
k=j%10;j/=10;
if(k==y) count++;
}
}
cout<<count<<endl;
return 0;
}
第二种,用字符串来解答会比较简便。字符串中有count函数,
count(ivec.begin() , ivec.end() , searchValue) ,这个函数作用是统计在一定范围内某一值出现的次数。那我们就可以把1-n的所有数转化为字符串,然后用count函数计算出现次数。
int a = 123, b = 456, c = 789;
stringstream ss;
ss << a << b << c;
以上几行把a b c三个变量读入字符串流中,这样就可以把a b c三个变量无缝衔接起来,但是需要注意的是,stringstream型不能直接输出,也不支持迭代器,需要利用stringstream类的成员函数str()才能把它当成普通字符串来用,例如
string s = ss.str();
而把字符串转为数值的话也是用stringstream,例如上面的ss就可以转换为一个int型
int i;
ss >> i;
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, x;
cin >> n >> x;
stringstream ss;
for (n++; --n; ss << n); //把1-n的值都存放到字符串流中
string s = ss.str();
cout << count(s.begin(), s.end(), x + '0') << endl;
return 0;
}