HDU2133 What day is it【日期】

本文介绍了一个简单的算法,用于计算任意给定日期对应的星期几。通过分析闰年和平年的天数差异,利用C语言实现了一个实用的程序,可以快速判断输入日期的合法性并返回相应的星期名称。

What day is it

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6518    Accepted Submission(s): 1934


Problem Description
Today is Saturday, 17th Nov,2007. Now, if i tell you a date, can you tell me what day it is ?
 

Input
There are multiply cases.
One line is one case.
There are three integers, year(0<year<10000), month(0<=month<13), day(0<=day<32).
 

Output
Output one line.
if the date is illegal, you should output "illegal". Or, you should output what day it is.
 

Sample Input
  
2007 11 17
 

Sample Output
  
Saturday
 

Author
LGX
 

Source

问题链接HDU2133 What day is it

问题简述:(略)

问题分析:(略)

程序说明

  假设西元0年1月1日为星期一的基础上进行计算。

  算出给定的日期到这一天经过了几天,计算是星期几就简单了。

题记:(略)

参考链接:(略)


AC的C语言程序如下:

/* HDU2133 What day is it */

#include <stdio.h>

const char *DAYS[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

int mdays[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int leapyear(int year)
{
    return ( ((year%4==0) && (year%100!=0)) || (year%400==0) ) ? 1 : 0;
}

int monthsum[] = {  /* 到某月份的天数,润年另外加天数 */
      0                                 /* 1月 */
    , 31                                /* 2月 */
    , 31+28                             /* 3月 */
    , 31+28+31                          /* 4月 */
    , 31+28+31+30                       /* 5月 */
    , 31+28+31+30+31                    /* 6月 */
    , 31+28+31+30+31+30                 /* 7月 */
    , 31+28+31+30+31+30+31              /* 8月 */
    , 31+28+31+30+31+30+31+31           /* 9月 */
    , 31+28+31+30+31+30+31+31+30        /* 10月 */
    , 31+28+31+30+31+30+31+31+30+31     /* 11月 */
    , 31+28+31+30+31+30+31+31+30+31+30  /* 12月 */
};

int leapyear_day(int year, int month)
{
    /* 1月或2月不用加1天,其他月份润年加1天,非润年不用加1天 */
    return month <= 2 ? 0 : leapyear(year);
}

int main()
{
    int y, m, d, days;

    while(~scanf("%d%d%d", &y, &m, &d)) {
        mdays[2] = 28 + leapyear(y);

        if(0 < y && y < 10000 && 1 <= m && m <= 12 && 1 <= d && d <= mdays[m]) {
            /* 计算当年的天数 */
            days = leapyear_day(y, m) + monthsum[m - 1] + d;

            for(int i=1; i<y; i++)
                days += 365 + leapyear(i);

            printf("%s\n", DAYS[days % 7]);
        } else
            printf("illegal\n");
    }

    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值