50
50
51
51
最后,根据给定的日期计算出当年的第几天,即把前面每个月的天数累加起来,再加上当月的天数即可。
52
52
53
- 时间复杂度为 $O(1)$,空间复杂度为 $O(1)$。
53
+ 时间复杂度 $O(1)$,空间复杂度 $O(1)$。
54
54
55
55
<!-- tabs:start -->
56
56
@@ -94,9 +94,8 @@ class Solution {
94
94
class Solution {
95
95
public:
96
96
int dayOfYear(string date) {
97
- int y = stoi(date.substr(0, 4));
98
- int m = stoi(date.substr(5, 2));
99
- int d = stoi(date.substr(8));
97
+ int y, m, d;
98
+ sscanf(date.c_str(), "%d-%d-%d", &y, &m, &d);
100
99
int v = y % 400 == 0 || (y % 4 == 0 && y % 100) ? 29 : 28;
101
100
int days[ ] = {31, v, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
102
101
int ans = d;
@@ -112,9 +111,8 @@ public:
112
111
113
112
```go
114
113
func dayOfYear(date string) (ans int) {
115
- y, _ := strconv.Atoi(date[:4])
116
- m, _ := strconv.Atoi(date[5:7])
117
- d, _ := strconv.Atoi(date[8:])
114
+ var y, m, d int
115
+ fmt.Sscanf(date, "%d-%d-%d", &y, &m, &d)
118
116
days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
119
117
if y%400 == 0 || (y%4 == 0 && y%100 != 0) {
120
118
days[1] = 29
@@ -127,6 +125,19 @@ func dayOfYear(date string) (ans int) {
127
125
}
128
126
```
129
127
128
+ ### ** TypeScript**
129
+
130
+ ``` ts
131
+ function dayOfYear(date : string ): number {
132
+ const y = + date .slice (0 , 4 );
133
+ const m = + date .slice (5 , 7 );
134
+ const d = + date .slice (8 );
135
+ const v = y % 400 == 0 || (y % 4 == 0 && y % 100 ) ? 29 : 28 ;
136
+ const days = [31 , v , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ];
137
+ return days .slice (0 , m - 1 ).reduce ((a , b ) => a + b , d );
138
+ }
139
+ ```
140
+
130
141
### ** JavaScript**
131
142
132
143
``` js
0 commit comments