4399面试题——计算天数
分类:Interview
题目:
小陆每天要写一份工作日报,日报标准是“入职第X天-小陆-XXX”,对于“入职第几天”,小陆现在每次需要对上次写的日报标题里的天数+1, 遇到周末还要多加2天等等。请你写一段程序,帮小陆自动完成这件事,提供写日期当天的年月日,算出已入职的天数(假定小陆的入职时间是
2014年8月18日)。要求:不能使用时间,日期相关的库函数。
分析:
先将时间封装成类,对于内部的操作采用private方法或者重载运算符的方式封装。计算时间差的时候,先计算年的天数;再加上该年的天数;再减去初始年的天数。
算法代码:
class Time { private: int _Year; int _Month; int _Day; const int LEAPYEARDAYS = 366; const int NONLEAPYEARDAYS = 365; bool isLeapYear(int year) const; int daysOfMonth(int month, int year) const; public: Time() {} Time(int y, int m, int d) : _Year(y), _Month(m), _Day(d) {} ~Time() {} int operator-(const Time & beginTime); friend istream & operator>>(istream & is, Time & inputTime); }; bool Time::isLeapYear(int year) const { if ((0 == year % 4) && (0 != year % 100)) { return true; } else { return false; } } int Time::daysOfMonth(int month, int year) const { switch (month) { case 2: if (isLeapYear(year)) { return 29; } else { return 28; } case 4: case 6: case 9: case 11: return 30; default: return 31; } } int Time::operator-(const Time & beginTime) { int continueDays = 0; //days between two years for (int i = 0; i < (this->_Year - beginTime._Year); ++i) { if (isLeapYear(this->_Year - i)) { continueDays += LEAPYEARDAYS; } else { continueDays += NONLEAPYEARDAYS; } } //days of this year for (int i = 1; i < this->_Month; ++i) { continueDays += daysOfMonth(i, this->_Year); } continueDays += this->_Day; //subtract days of beginTime for (int i = 1; i < beginTime._Month; ++i) { continueDays -= daysOfMonth(i, beginTime._Year); } continueDays -= beginTime._Day; return continueDays; } istream & operator>>(istream & is, Time & inputTime) { is >> inputTime._Year >> inputTime._Month >> inputTime._Day; return is; }
测试代码:
// // main.cpp // calculateDays // // Created by Jiajie Zhuo on 2017/4/5. // Copyright © 2017年 Jiajie Zhuo. All rights reserved. // #include <iostream> using namespace std; int main(int argc, const char * argv[]) { Time beginTime(2014, 8, 18); Time currentTime; cout << "Please input the current time(year, month, day): "; cin >> currentTime; int continueDays; continueDays = currentTime - beginTime; cout << "He has been entered for " << continueDays << endl; return 0; }
总结:
利用了OOP的思想将时间类封装,计算天数时分别计算年月日能够简化思维的复杂度。对判断平年闰年以及不同月份的天数操作进行方法封装。
如果有收获,可以请我喝杯咖啡!