Leetcode每日一题 2023/12/331 一年中的第几天
题目
给你一个字符串 date
,按 YYYY-MM-DD
格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
示例 1:
输入:date = "2019-01-09"
输出:9
解释:给定日期是2019年的第九天。
示例 2:
输入:date = "2019-02-10"
输出:41
提示:
date.length == 10
date[4] == date[7] == '-'
,其他的date[i]
都是数字date
表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日
分析
- 首先将字符串分割得到year、month、day的字符串再转成int数值。
- 确定当前年份是不是闰年,如果是闰年,2月份有29天。
- 将1-到month-1月的天数全部加上,再加上day得到最终天数。
闰年计算方式:年份是4的倍数不是100的倍数,例如2016。或者是400的倍数,例如2000年。
1-到month-1月的天数,映射到数组中就是0-month-2,数组下标从0开始
编码
class Solution {
int [] monDay = {31,28,31,30,31,30,31,31,30,31,30,31};
public int dayOfYear(String date) {
int total = 0;
String[] split = date.split("-");
int year = Integer.parseInt(split[0]);
int day = Integer.parseInt(split[2]);
int mon = Integer.parseInt(split[1]);
total+=day;
if((year%4==0&&year%100!=0)||year%400==0){
monDay[1] = 29;
}
for (int i = 0; i < mon-1; i++) {
total+=monDay[i];
}
return total;
}
}
交流
年底了,leetcode官方也是连续出了好几天简单题,为了不影响大家跨年心情(个人观点,哈哈)
qq群一起交流编程技术鸭: