(Easy) Day of the Year - LeetCode

Description

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

 

Example 1:

Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.

Example 2:

Input: date = "2019-02-10"
Output: 41

Example 3:

Input: date = "2003-03-01"
Output: 60

Example 4:

Input: date = "2004-03-01"
Output: 61

 

Constraints:

  • date.length == 10
  • date[4] == date[7] == '-', and all other date[i]'s are digits
  • date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.

Solution

class Solution {
    public int dayOfYear(String date) {
        
        if(date ==null || date.length()==0){
            return 0;
        }
        
        //judge whether Februray has 28 or 29 days.
      
        //yyyy-mm-dd
        String year = date.substring(0,4);
        
        
        String month = date.substring(5,7);
  
        String day = date.substring(8,10);
        
        int months = Integer.valueOf(month);
        int years = Integer.valueOf(year);
        int days = Integer.valueOf(day);
        int sum = 0;
         //1,3,5,7,8,10,12 
        Map<Integer,Integer> map = new HashMap<Integer, Integer> ();
        map.put(1,31);
        map.put(3,31);
        map.put(4,30);
        map.put(5,31);
        map.put(6,30);
        map.put(7,31);
        map.put(8,31);
        map.put(9,30);
        map.put(10,31);
        map.put(11,30);
        map.put(12,31);
        for(int i =1; i<months;i++){
            
            if(i!=2){
                
                 sum = sum+ map.get(i);
            }
            else{
                
                if(LeapYear(years)){
                    
                    sum = sum +29;
                }
                else 
                {
                    sum = sum +28;
                }
            }
        }
 
        //judge whether Februray has 28 or 29 days.
 
        return sum +days;
    }
    
    public boolean LeapYear(int year){
         boolean isLeapYear;

        // divisible by 4
        isLeapYear = (year % 4 == 0);

        // divisible by 4 and not 100
        isLeapYear = isLeapYear && (year % 100 != 0);

        // divisible by 4 and not 100 unless divisible by 400
        isLeapYear = isLeapYear || (year % 400 == 0);

      return isLeapYear;

    }
}

 

posted @ 2019-08-12 17:03  CodingYM  阅读(272)  评论(0编辑  收藏  举报