본문 바로가기

백준1308 - D-Day node.js 본문

개발/algorithm

백준1308 - D-Day node.js

자전하는명왕성 2024. 2. 12. 10:15

https://www.acmicpc.net/problem/1308

자바스크립트로 해결된 포스팅이 없어 포스팅하게 됨.

 

문제 풀이 방식

시작 날짜의 총 날짜와, 끝 날짜의 총 날짜를 깡으로 구해서 그 차이를 출력하는 방식으로 접근하였다. 문제에서 말하는 윤년 기준을 적용하는 방식이 은근히 까다로웠던 문제.

 

전체 소스 코드

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "입력.txt")
  .toString()
  .trim()
  .split("\n");

function solution(data) {
  const [[sy, sm, sd], [ey, em, ed]] = data.map((el) =>
    el.split(" ").map(Number)
  );

  if (sy + 1000 < ey || (sy + 1000 == ey && sm <= em && sd <= ed)) {
    console.log("gg");
    return;
  }

  const start = getDays(sy, sm, sd),
    end = getDays(ey, em, ed);

  console.log(`D-${end - start}`);
}

function verifyYear(y) {
  if (y % 4 === 0) {
    if (y % 100 === 0 && y % 400 !== 0) return false;
    else return true;
  }
  return false;
}

function getDays(y, m, d) {
  let cnt = d;
  const monthDays = [
    31,
    verifyYear(y) ? 29 : 28,
    31,
    30,
    31,
    30,
    31,
    31,
    30,
    31,
    30,
    31,
  ];

  for (let i = 0; i < y; i++) cnt += 365 + verifyYear(i);
  for (let i = 0; i < m - 1; i++) cnt += monthDays[i];

  return cnt;
}

solution(input);
Comments