这道题刚刚做过没几个周,昨天考试碰到这个题了,但当时运行string函数以及while都不行,于是便开始了漫长的暴力……
题目描述
试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)共出现了多少次?
例如,在 1到 11 中,即在 1、2、3、4、5、6、7、8、9、10、11 中,数字 1 出现了 4 次。
输入输出格式
输入格式:
输入文件名为 count.in。
输入共 1 行,包含 2 个整数 n、x,之间用一个空格隔开。
输出格式:
输出文件名为 count.out。
输出共 1 行,包含一个整数,表示 x 出现的次数。
输入输出样例
输入样例#1:
11 1
输出样例#1:
4
说明
对于 100%的数据,1≤ n ≤ 1,000,000,0 ≤ x ≤ 9。
正确的代码:
1 #include <cstdio> 2 3 int main() { 4 //freopen("cishu.in", "r", stdin); 5 //freopen("cishu.out", "w", stdout); 6 int n, x, ans = 0; 7 scanf("%d%d", &n, &x); 8 for (int i = 1; i <= n; ++i) { 9 int p = i; 10 while (p) { //检查p是否为0,即是否还有更高的位数 11 int q = p % 10;//q取p的最低一位 12 if (q == x) ++ans;//如果最低一位符合要求那么记录一下 13 p /= 10;//p不断去掉最后一位 14 } 15 } 16 printf("%d", ans); 17 return 0; 18 }
考试路上的暴力(只得了20分):
1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<iostream> 5 using namespace std; 6 long a[1000005]; 7 int t=0; 8 inline int cs(int n,int x) { 9 for(int i=1; i<=n; i++) { 10 if(i<=9) 11 if(i==x) t++; 12 else { 13 for(int j=1; j<=6; j++) { 14 int q,p;//q储存余数 15 p=i/(10^j); 16 q=p%(10^j); 17 if(q<=9&&q>=0) 18 if(q==x) t++; 19 } 20 } 21 } 22 } 23 int main() { 24 //freopen("cishu.in","r",stdin); 25 //freopen("cishu.out","w",stdout); 26 int n,x; 27 cin>>n>>x; 28 cs(n,x); 29 cout<<t<<endl; 30 return 0; 31 }
以后做题一定要勤复习啊!
原文:https://www.cnblogs.com/zhengyongle506/p/10698234.html