2550: 记数问题
Time Limit: 10000MS Memory Limit: 131072KBTotal Submit: 37 Accepted: 22 Page View: 30
Submit Status Discuss
Description
试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)共出现了多少次?例如,在 1 到 11 中,即在 1、2、3、4、5、6、7、8、9、10、11 中,数字 1 出现了 4 次。
Input
输入共 1 行,包含 2 个整数 n、x,之间用一个空格隔开
Output
输出共 1 行,包含一个整数,表示 x 出现的次数。
11 1
4
Hint
对于 100%的数据,1≤ n ≤ 1,000,000,0 ≤ x ≤ 9。
Source
一个很心累的题,我花了近两个小时在计算公式,还区分了0和其他数字的不同,结果。。。。。。。。。。。。只需要一轮循环就可以了,因为最大也就1000000,一轮循环不会超时的,所以直接把每个数字拿来进行比对累加就行。
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int n,m,ans=0;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
int a=i;
for(int j=0;a>0;j++)
{
int x=a%10;
if(x==m)
ans++;
a/=10;
}
}
printf("%d\n",ans);
return 0;
}