计算日期到天数转换

计算日期到天数转换

http://www.nowcoder.com/questionTerminal/769d45d455fe40b385ba32f97e7bcded

import java.util.Scanner;

public class Main {

    private int leapMonth[] = {0, 31,29,31,30,31,30,31,31,30,31,30,31};
    private int normalMonth[] = {0, 31,28,31,30,31,30,31,31,30,31,30,31};
    private int result;

    public Main() {        
    }

    public int iConverDateToDay(int year, int month, int day) {
        if (year <= 0 || month <= 0 || month > 12 || day <= 0) {
            return result = -1;
        }

        boolean isLeapYear = false;
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            isLeapYear = true;
        }
        if (isLeapYear && day > leapMonth[month]) {
            return result = -1;
        }
        if (!isLeapYear && day > normalMonth[month]) {
            return result = -1;
        }
        result = 0;
        for (int i = 1; i < month; i++) {
            if (isLeapYear) {
                result += leapMonth[i];
            }
            else {
                result += normalMonth[i];
            }
        }
        result += day;
        return 0;        
    }

    public int getOutDay() {
        return result;
    }

    public static void main(String[] args) {
        Main solution = new Main();
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int year = in.nextInt(), month = in.nextInt(), day = in.nextInt();
            solution.iConverDateToDay(year, month, day);
            int result = solution.getOutDay();
            System.out.println(result);
        }
    }
}
全部评论

相关推荐

评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务