题解 | #计算日期到天数转换#
计算日期到天数转换
https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
照例先分享不用动脑筋的简单算法,再附上比较巧妙的算法:
//算法1: 二狗算法(太简单了,就不解析了,解析一下第二种算法) while (line = readline()) { let arr = line.split(' '); let n = parseInt(arr[0]); let m = parseInt(arr[1]); let d = parseInt(arr[2]); let base = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let output = 0; if (m == 1) { output = d; //console.log("A"); } else if (m == 2) { output = 31 + d; //console.log("B"); } else { if (n % 4 == 0 && n % 100 != 0) { output = base.slice(0, m - 1).reduce((a, b) => a+b) + d + 1; //console.log("C"); } else { output = base.slice(0, m - 1).reduce((a, b) => a+b) + d; //console.log("D"); } } console.log(output); } //算法2:巧妙算法 /* var arr = readline().split(' ') var year = arr[0] var month = arr[1] var day = arr[2] var sum = 0 for(var i = month-1; i > 0; i--) { //这里的for循环是关键,new Date(year, i, 0)可以定位到year年i+1月最后一天, //再通过getDate()方法即可获取当月天数,再通过+=方法,得出sum,再加上day输出即可。 sum += new Date(year, i, 0).getDate() //console.log(sum); } console.log(sum+Number(day)); */