algorithms
时隔一月重新开始leetcode周赛,被教做人....做题进度0/4,有点扎心
number-of-days-between-two-dates
description
搞了半天,没搞明白,看别人题解吧~
请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。
示例 1:
输入:date1 = "2019-06-29", date2 = "2019-06-30"
输出:1
示例 2:
输入:date1 = "2020-01-15", date2 = "2019-12-31"
输出:15
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-days-between-two-dates
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
my solution
解决思路,计算两个日期分别距离1970-01-01多少天,再计算差值
class Solution {
public:
vector<int> months = {-1,31,28,31,30,31,30,31,31,30,31,30,31};
int daysBetweenDates (string date1, string date2) {
return abs(getdays(date1)-getdays(date2));
}
int isleap(int year){
return year%4==0 && year%100!=0 || year%400==0;
}
int getdays(string date) {
int year = 0, month = 0, day = 0;
for (int i=0; i<4; ++i) {
year = year*10 + date[i]-'0';
}
for (int i=5; i<7; ++i) {
month = month*10 + date[i]-'0';
}
for (int i=8;i<date.size(); ++i) {
day = day*10 + date[i]-'0';
}
int result = 0;
for (int i=1970; i<year; ++i) {
result += isleap(i)? 366:365;
}
for (int i=1; i<month; ++i) {
result += months[i];
if (i==2 && isleap(year)) {
result++;
}
}
result += day;
return result;
}
};
complexity
Review
How To Ask Questions The Smart Way
original link
Tips
开始学Java
C++
Vectors are sequence containers representing arrays that can change in size.
Java
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
我看着这俩没啥区别哈?
网友评论