下午有点感冒,挑了个简单的题刷来打发时间,然后被大神教做人
题目:
Given a string date
representing a Gregorian calendar date formatted as YYYY-MM-DD
, return the day number of the year.
Example 1:
Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:
Input: date = "2019-02-10"
Output: 41
Example 3:
Input: date = "2003-03-01"
Output: 60
Example 4:
Input: date = "2004-03-01"
Output: 61
Constraints:
date.length == 10
date[4] == date[7] == '-'
, and all otherdate[i]
's are digitsdate
represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.
我的解法(java)
public static int dayOfYear(String date) {
int num=0;
int[] monthDay={31,28,31,30,31,30,31,31,30,31,30,31};
String[] arr=date.split("-");
int year=Integer.parseInt(arr[0]);
int month=Integer.parseInt(arr[1]);
int day=Integer.parseInt(arr[2]);
//deal with leap year
if(year%100==0&&year%400==0)
monthDay[1]=29;
if(year%100!=0&&year%4==0)
monthDay[1]=29;
for(int i=0;i<month-1;i++){
num=num+monthDay[i];
}
return num+day;
}
神奇思路(python)
def ordinalOfDate(self, date):
Y, M, D = map(int, date.split('-'))
return int((datetime.datetime(Y, M, D) - datetime.datetime(Y, 1, 1)).days + 1)
顺便学习一下python中map这个强大的函数
map() 函数语法:
map(function, iterable, ...)
- function -- 函数
- iterable -- 一个或多个序列
实例
>>>def square(x) : # 计算平方数
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]