1154. Day of the Year

下午有点感冒,挑了个简单的题刷来打发时间,然后被大神教做人

题目:

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 other date[i]'s are digits
  • date 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]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值