-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathday of the year.cpp
More file actions
78 lines (70 loc) · 2 KB
/
day of the year.cpp
File metadata and controls
78 lines (70 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Runtime: 4 ms, faster than 57.01% of C++ online submissions for Day of the Year.
// Memory Usage: 8.5 MB, less than 100.00% of C++ online submissions for Day of the Year.
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
class Solution
{
public:
std::vector<std::string> string_split(std::string str, std::string delimiter)
{
size_t pos = 0;
std::string token;
std::vector<std::string> result;
while ((pos = str.find(delimiter)) != std::string::npos)
{
token = str.substr(0, pos);
result.push_back(token);
str.erase(0, pos + delimiter.length());
}
result.push_back(str);
return result;
}
int dayOfYear(string date)
{
vector<string> vs = string_split(date, "-");
vector<int> ymd;
int ans;
std::transform(vs.begin(), vs.end(), std::back_inserter(ymd),
[](const std::string &s)
{ return std::stoi(s); });
ans = ymd[2]; // d
for (int m = 1; m < ymd[1]; m++)
{
if (m == 2)
{
ans += 28;
if (ymd[0] % 400 == 0)
{
ans += 1;
}
else if (ymd[0] % 100 == 0)
{
// 100's multiple, not 400's multiple
// is not leap year
}
else if (ymd[0] % 4 == 0)
{
ans += 1;
}
}
else if (m < 8)
{
if (m % 2 == 1)
ans += 31;
else
ans += 30;
}
else
{
if (m % 2 == 1)
ans += 30;
else
ans += 31;
}
}
return ans;
}
};