日历中的数字

题目描述
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;
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值