POJ2080--Calendar以及一个类似的编程面试题

问题链接:http://poj.org/problem?id=2080

代码:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

bool bIsLeapYear(int iYear)
{
	if(iYear%4==0 && iYear%100!=0  ||  iYear%400==0) return 1;
	else return 0;
}
int main()
{
	int iYearDates[2]={365,366};
	int iMonthDates[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};
	string strWeek[7]={"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};//2000.1.1 is "Saturday"
	int iYear=0,iMonth=0,iDayOfWeek=0;
	int iDays;
	while(cin>>iDays && iDays!=-1)
	{
		iDayOfWeek=iDays%7;
		for(iYear=2000;;iYear++) 
		{
			int temp=iYearDates[bIsLeapYear(iYear)];
			if(iDays<temp)  break;
			iDays-=temp;
		}
		for(iMonth=0;;iMonth++)
		{
			int temp=iMonthDates[bIsLeapYear(iYear)][iMonth];
			if(iDays<temp)  break;
			iDays-=temp;
		}
		cout<<iYear<<"-"<<setfill('0')<<setw(2)<<iMonth+1<<"-"<<setfill('0')<<setw(2)<<iDays+1<<" "<<strWeek[iDayOfWeek]<<endl;
	}
	return 1;
}


编程面试题:求两个时间之间的天数,不能用系统函数。

/* 是否是闰年; */
bool is_leap_year(int year)  
{  
	if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) return 1;  
	else return 0;  
}  
  
int year_days[2] = { 365,366 };  
int month_days[2][12] = { { 31,28,31,30,31,30,31,31,30,31,30,31 },{ 31,29,31,30,31,30,31,31,30,31,30,31 } };  
/* 1900.1.1 is monday; */  
char week[7][10] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};  
  
/* 返回2016.12.16形式的日期距离1900.1.1的天数; */  
int daydiff_base(char d[]) {  
    int date[3] = { 0 };  
    int i = 0;  
    char *token = strtok(d, ".");  
    while (token) {  
        sscanf(token, "%d", &date[i++]);  
        token = strtok(NULL, ".");  
    }  
  
    int day_cnt = 0;  
    for (int year = 1900; year < date[0]; year++) {  
        day_cnt += year_days[is_leap_year(year)];  
    }  
  
    for (int month = 1; month < date[1]; month++) {  
        day_cnt += month_days[is_leap_year(date[0])][month-1];  
    }  
  
    day_cnt += date[2]-1;  
  
    return day_cnt;  
}  
 
/* 返回2016.12.16形式的日期星期数在week数组里的index; */  
int week_index(char d[]) {  
    return daydiff_base(d)%7;  
} 

/* 返回2016.12.16形式的日期d1-d2的天数; */  
int datediff(char d1[], char d2[]) {  
    return daydiff_base(d1) - daydiff_base(d2);  
}  
/*注意使用;*/
/* Result in crash at daydiff_base; */  
//printf("%s - %s = %d days.\n", "1900.1.2", "1900.1.1", datediff("1900.1.2", "1900.1.1"));  
char d1[] = "2016.12.16";  
char d2[] = "2016.11.16";  
printf("%s - %s = ", d1, d2);  
printf("%d days.\n", datediff(d1, d2));


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值