Java/Algorithm

[Java-Algorithm] HackerRank Java Date and Time 풀이

Jeong Jeon
반응형

1). 문제 : www.hackerrank.com/challenges/java-date-and-time

 

Java Date and Time | HackerRank

Print the day of a given date.

www.hackerrank.com

2). 풀이 : 

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

class Result {

    /*
     * Complete the 'findDay' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts following parameters:
     *  1. INTEGER month
     *  2. INTEGER day
     *  3. INTEGER year
     */

     public static String findDay(int month, int day, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, day);
        cal.set(Calendar.YEAR, year);

        String[] day_of_week = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY","SATURDAY"};
        
        return day_of_week[cal.get(Calendar.DAY_OF_WEEK)-1];
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int month = Integer.parseInt(firstMultipleInput[0]);

        int day = Integer.parseInt(firstMultipleInput[1]);

        int year = Integer.parseInt(firstMultipleInput[2]);

        String res = Result.findDay(month, day, year);

        bufferedWriter.write(res);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}
  • Calendar 객체를 사용하여 날짜를 Set 해준다.
    • Month-1을 해준것은 Java Calendar 객체는 1월을 0으로 취급하기 때문에 한칸씩 민것이라고 생각하면 된다.
  • 일주일의 요일 배열을 생성한다.
  • Calendar객체의  .get(Calendar.Day_OF_WEEK)으로 원하는 날짜의 요일 index를 뽑아낸다.
  • 배열에서 뽑아낸 index를 찾아내면 끝
반응형