vijos p1848 记数问题
描述
试计算在区间 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
样例输入1
11 1
Copy
样例输出1
4
Copy
限制
每个测试点1s。
提示
对于 100%的数据,1≤ n ≤ 1,000,000,0 ≤ x ≤ 9。
来源
NOIP 2013 普及组
思路
直接模拟
代码
1.(int数组 取模方式)
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main() 5 { 6 long n,i,l,j; 7 int a[11]; 8 int x,p; 9 int cnt=0; 10 scanf ("%ld%d",&n,&x); 11 for (j=1;j<=n;j++) { 12 p=j; 13 l=0; 14 while (p) { 15 a[l]=p%10; 16 l++; 17 p=p/10; 18 } 19 for (i=0;i<l;i++) { 20 if (a[i]==x) { 21 cnt++; 22 } 23 } 24 } 25 printf("%d\n",cnt); 26 return 0; 27 }
2.字符串方式
1 #include <stdio.h> 2 #include <string.h> 3 4 int main() 5 { 6 long n; 7 int x,i,j,len,cnt; 8 char s[20]; 9 cnt=0; 10 scanf ("%ld%d",&n,&x); 11 for (i=1;i<=n;i++) { 12 sprintf (s,"%d",i); 13 len = strlen(s); 14 for (j=0;j<len;j++) { 15 if (s[j]-'0'==x) cnt++; 16 } 17 } 18 printf("%d\n",cnt); 19 return 0; 20 }