• [LC] 1360. Number of Days Between Two Dates


    Write a program to count the number of days between two dates.

    The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

    Example 1:

    Input: date1 = "2019-06-29", date2 = "2019-06-30"
    Output: 1
    

    Example 2:

    Input: date1 = "2020-01-15", date2 = "2019-12-31"
    Output: 15
    

    Constraints:

    • The given dates are valid dates between the years 1971 and 2100.
    class Solution {
        public int daysBetweenDates(String date1, String date2) {
            return Math.abs(calculateDays(date1) - calculateDays(date2));
        }
        
        private int calculateDays(String date) {
            int[] monthDays = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
            String[] dateArr = date.split("-");
            int year = Integer.parseInt(dateArr[0]);
            int month = Integer.parseInt(dateArr[1]);
            int day = Integer.parseInt(dateArr[2]);
            int res = day;
            for (int i = 1971; i < year; i++) {
                if (isLeap(i)) {
                    res += 366;
                } else {
                    res += 365;
                }
            }
            for (int i = 1; i < month; i++) {
                if (isLeap(year) && i == 2) {
                    res += 1;
                }
                res += monthDays[i];
            }
            return res;
        }
        
        private boolean isLeap(int year) {
            return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
        }
    }
  • 相关阅读:
    luogu 2617
    BZOJ 3295
    BZOJ 2458
    luogu 3810
    Uva
    Uva
    Uva
    Uva
    Uva
    成员函数的const到底修饰的是谁
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12791499.html
Copyright © 2020-2023  润新知