题解 | #今年的第几天?# #Java#
今年的第几天?
https://www.nowcoder.com/practice/ae7e58fe24b14d1386e13e7d70eaf04d
import java.util.Scanner; import java.util.HashSet; import java.util.Set; import java.util.Arrays; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int year = in.nextInt(); int month = in.nextInt(); int day = in.nextInt(); int res = getDays(year,month,day); System.out.println(res); } } public static int getDays(int year, int month, int day) { Set<Integer> bigMonth = new HashSet<Integer>(Arrays.asList(1, 3, 5, 7, 8, 10,12)); Set<Integer> smallMonth = new HashSet<Integer>(Arrays.asList(4, 6, 9, 11)); int res = 0; // 判断是否是闰年 if(year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0)){ // 如果是闰年,且当月大于二月,则加一天 if(month > 2){ res += 1; } } for(int i = 0;i < month-1;i++ ){ int tm = i+1; if(tm == 2){ res += 28; }else{ if(bigMonth.contains(tm)){ res += 31; }else{ res += 30; } } } return res+day; } }