题目描述
ElemenT马上就要毕业了,他打开日历看了看时间。发现日历上的日期都是2017-04-04这样的格式的,月和日如果不足2位数,前面都会补充0。
给定一个年份和月份,ElemenT把那个月的日期都按上述格式写到纸上,他现在想知道某种数字出现了多少次。
输入描述:
多组输入
每组输入一行,有3个数字y,m,x(1000<=y<=3000,1<=m<=12,0<=x<=9),分别代表年份,月份,和他想知道哪个数字出现的次数。
输出描述:
每组输出一个整数,表示数字x在这个月的日期里出现了多少次。
示例1
输入
复制
2017 4 4
2000 1 0
输出
复制
33
我也不知道,2333
说明
第一组样例中,日中有数字4的为2017-04-04,2017-04-14,2017-04-24,4月一共有30天,因为月份中有4,所以数字4一共出现了30 + 3 = 33次
思路:就是一个枚举,找出所有符合的解,我的代码写的比较烂,其实在找的时候可以直接写个函数。用一个数组放每个月的天数。因为二月份的天数与是否是闰年有关,所有要先判断一下x是不是闰年。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int y,m,x;
while(cin>>y>>m>>x)
{
int ans=0;
int a[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
if((y%4==0&&y%100!=0)||(y%400)==0) a[1]=29;
int count1=0;
int l=y;
while(l)
{
int s=l%10;
l=l/10;
if(s==x) count1++;
}
ans += a[m-1]*count1;
int m1=m;
if(m1<10)
m1=m1*10;
int count2=0;
while(m1)
{
int s=m1%10;
m1=m1/10;
if(s==x) count2++;
}
ans += a[m-1]*count2;
int count3=0;
for(int i=1; i<=a[m-1]; i++)
{
int j = i;
if(j<10)
j=j*10;
while(j)
{
int s=j%10;
j=j/10;
if(s==x) count3++;
}
}
ans +=count3;
cout<<ans<<endl;
}
return 0;
}
改进后的版本
#include<bits/stdc++.h>
using namespace std;
int mon[13]= {0,31,28,31,30,31,30,31,31,30,31,30,31};
int x;
int fun(int n)
{
int l=0,cnt=0;
while(n)
{
l++;
if(n%10==x)
{
cnt++;
}
n=n/10;
}
if(l==1 && x==0)
{
cnt++;
}
return cnt;
}
using namespace std;
int main()
{
int i,n,m;
while(cin>>n>>m>>x)
{
int ans=0;
if( (n%4==0 && n%100!=0 ) || n%400==0)
{
mon[2]=29;
}
for(i=1; i<=mon[m]; i++)
{
ans=ans+fun(n)+fun(m)+fun(i);
}
mon[2]=28;
cout<<ans<<endl;
}
return 0;
}