<p/><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/53085f236a3cdb6d.jpg" contenteditable="false" img-data="{"format":"jpeg","size":168231,"height":900,"width":1600}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><p>
</p><blockquote><p>给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。请你计算并返回该日期是当年的第几天。
通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。
示例 1:
输入:date = "2019-01-09"
输出:9
示例 2:
输入:date = "2019-02-10"
输出:41
示例 3:
输入:date = "2003-03-01"
输出:60
示例 4:
输入:date = "2004-03-01"
输出:61
提示:
date.length == 10
date[4] == date[7] == '-',其他的 date[i] 都是数字
date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/day-of-the-year
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。</p></blockquote><p>
</p><h1 id="2z43d">题解</h1><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/152b7133604c5956.jpg" contenteditable="false" img-data="{"format":"jpeg","size":25678,"height":386,"width":658}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><p>
</p><h2>Swift</h2><blockquote><p>class Solution {
func dayOfYear(_ date: String) -> Int {
var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
let time = date.split(separator: "-")
let year = Int(time[0])!, month = Int(time[1])!, day = Int(time[2])!
var result = 0
if year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) {
monthDays[1] += 1
}
for m in 0 ..< month - 1 {
result += monthDays[m]
}
return result + day
}
}
//print(Solution().dayOfYear("2019-01-09"))
//
//print(Solution().dayOfYear("2019-02-10"))
//
//print(Solution().dayOfYear("2003-03-01"))
print(Solution().dayOfYear("2012-01-02"))
</p></blockquote><p>
</p><h2>Dart</h2><blockquote><p>class Solution {
int dayOfYear(String date) {
var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var time = date.split("-");
var year = int.parse(time[0]),
month = int.parse(time[1]),
day = int.parse(time[2]);
var result = 0;
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
monthDays[1] += 1;
}
for (var i = 0; i < month - 1; i++) {
result += monthDays[i];
}
return result + day;
}
}
void main() {
print(Solution().dayOfYear("2019-01-09"));
print(Solution().dayOfYear("2019-02-10"));
print(Solution().dayOfYear("2003-03-01"));
print(Solution().dayOfYear("2012-01-02"));
}
</p></blockquote><p>
</p><p>
</p>
网友评论