【codeup】1928.日期差值

【codeup】1928.日期差值

有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。

输入:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD

输出:
每组数据输出一行,即日期差值

样例输入:
20130101
20130105

样例输出:
5

异或运算实现两个数的交换

题解

模拟:从小日期数到大日期

import java.util.*;

public class Solution2 {

    //闰平年的天数,填入一个二维数组中,方便直接调用
    public static int[][] month = new int[][]{
            {0, 0},
            {31, 31}, {28, 29}, {31, 31},
            {30, 30}, {31, 31}, {30, 30},
            {31, 31}, {31, 31}, {30, 30},
            {31, 31}, {30, 30}, {31, 31}};

    //判断是不是闰年
    public static int isLeap(int year) {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int time1, time2;
        //开始时间
        time1 = in.nextInt();
        //结束时间
        time2 = in.nextInt();

        //比较两个日期大小
        if (time1 > time2) {
            time1 ^= time2;
            time2 ^= time1;
            time1 ^= time2;
        }

        //提取年月日
        int year1 = time1 / 10000;
        int year2 = time2 / 10000;
        int month1 = time1 % 10000 / 100;
        int month2 = time2 % 10000 / 100;
        int day1 = time1 % 100;
        int day2 = time2 % 100;


        int ans = 1;
        while (year1 < year2 || month1 < month2 || day1 < day2) {
            day1++;
            if (month[month1][isLeap(year1)] + 1 == day1) {
                month1++;
                day1 = 1;
            }
            if (month1 == 13) {
                year1++;
                month1 = 1;
            }
            ans++;
        }
        System.out.println(ans);
    }
}  

你可能感兴趣的:(Java相关,#,力扣及OJ,算法,数据结构)