Number of Days Between Two Dates LeetCode solution in C++

1
class Solution {
2
public:
3
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
4
bool isLeap(int y) {
5
return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
6
}
7
int calc(string s) {
8
int y = stoi(s.substr(0, 4));
9
int m = stoi(s.substr(5, 2));
10
int d = stoi(s.substr(8));
11
for (int i = 1971; i < y; i++) d += isLeap(i) ? 366 : 365;
12
d += accumulate(begin(days), begin(days) + m - 1, 0);
13
d += (m > 2 && isLeap(y)) ? 1 : 0;
14
return d;
15
}
16
int daysBetweenDates(string date1, string date2) {
17
int ans = abs(calc(date2) - calc(date1));
18
return ans;
19
}
20
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0