- 输入:date = “2019-01-09”
输出:9
解释:给定日期是2019年的第九天。
python
class Solution(object):
def dayOfYear(self, date):
year, month, day = map(int, date.split('-'))
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
days[1] = 29
i = 0
sum = 0
for i in range(0, month - 1):
sum = sum + days[i]
return sum + day
执行时间:128ms
- 总体思路
(1)首先将年、月、日转换成整数形式,这里利用map进行一一映射,且把连接符去掉,只剩下数字
(2)再定义12个月份的天数
(3)再进行判断是否是闰年,因为闰年的话2月份是29天
(4)然后进行数组遍历,得到天数
Java
class Solution {
public int dayOfYear(String date) {
int year = Integer.parseInt(date.substring(0,4));
int month = Integer.parseInt(date.substring(5,7));
int day = Integer.parseInt(date.substring(8));
int num[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int sum = 0;
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
++num[1];
}
for(int i = 0; i < month - 1; i++){
sum = sum + num[i];
}
return sum + day;
}
}
执行时间:7ms
- 总体思路
(1)首先将年、月、日转换成整数形式
(2)再定义12个月份的天数
(3)再进行判断是否是闰年,因为闰年的话2月份是29天
(4)然后进行数组遍历,得到天数