To find the day of the year for a given date, sum the days in all previous months and add the day of the current month. For leap years, February has 29 days.
classSolution {
public:int dayOfYear(string date) {
int y = stoi(date.substr(0,4)), m = stoi(date.substr(5,2)), d = stoi(date.substr(8,2));
vector<int> days = {31,28,31,30,31,30,31,31,30,31,30,31};
if ((y%4==0&& y%100!=0) || (y%400==0)) days[1]=29;
int ans = d;
for (int i =0; i < m-1; ++i) ans += days[i];
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
import"strconv"funcdayOfYear(datestring) int {
y, _:=strconv.Atoi(date[:4])
m, _:=strconv.Atoi(date[5:7])
d, _:=strconv.Atoi(date[8:])
days:= []int{31,28,31,30,31,30,31,31,30,31,30,31}
if (y%4==0&&y%100!=0) || (y%400==0) { days[1]=29 }
ans:=dfori:=0; i < m-1; i++ { ans+=days[i] }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintdayOfYear(String date) {
int y = Integer.parseInt(date.substring(0,4));
int m = Integer.parseInt(date.substring(5,7));
int d = Integer.parseInt(date.substring(8,10));
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
if ((y%4==0 && y%100!=0) || (y%400==0)) days[1]=29;
int ans = d;
for (int i = 0; i < m-1; i++) ans += days[i];
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
fundayOfYear(date: String): Int {
val y = date.substring(0,4).toInt()
val m = date.substring(5,7).toInt()
val d = date.substring(8,10).toInt()
val days = intArrayOf(31,28,31,30,31,30,31,31,30,31,30,31)
if ((y%4==0&& y%100!=0) || (y%400==0)) days[1]=29var ans = d
for (i in0 until m-1) ans += days[i]
return ans
}
}
1
2
3
4
5
6
classSolution:
defdayOfYear(self, date: str) -> int:
y, m, d = int(date[:4]), int(date[5:7]), int(date[8:])
days = [31,28,31,30,31,30,31,31,30,31,30,31]
if (y%4==0and y%100!=0) or (y%400==0): days[1]=29return d + sum(days[:m-1])
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfnday_of_year(date: String) -> i32 {
let y: i32= date[0..4].parse().unwrap();
let m: usize= date[5..7].parse().unwrap();
let d: i32= date[8..].parse().unwrap();
letmut days = [31,28,31,30,31,30,31,31,30,31,30,31];
if (y%4==0&& y%100!=0) || (y%400==0) { days[1]=29; }
d + days[..m-1].iter().sum::<i32>()
}
}