题解 | 计算日期到天数转换
解题思路:
- 思路比较简单: 存储一个每个月份有多少的天的数组,累加即可
- 特殊情况:
- 闰年的判断:
- 普通闰年: 普通年份能被 4 整除但不能被 100 整除的为闰年
- 世纪闰年:世纪年能被 400 整除的是闰年,并且被100整除
b. 如果闰年就增加一天,但前提是月份的值大于2
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] nums = in.nextLine().split(" "); int[] monthDays = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int year = Integer.parseInt(nums[0]); int month = Integer.parseInt(nums[1]); int day = Integer.parseInt(nums[2]); int total = 0; for (int i = 0; i < month - 1; i++) { total += monthDays[i]; } if (year % 100 != 0 && year % 4 == 0 && month > 2) { total += 1; } if (year % 100 == 0 && year % 400 == 0 && month > 2) { total += 1; } total += day; System.out.println(total); } }