[#14][알고리즘] 2016년, 요일 구하는 알고리즘

프로그래머스(Programmers) > 2016년, 요일 구하기

문제 링크(https://programmers.co.kr/learn/challenge_codes/175)
















C++ 풀이
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string getDayName(int a,int b)
{
  string answer= "";
  vector<string> dayname = {"FRI","SAT","SUN","MON","TUE","WED","THU"};
  int monthdays[12= {31,60,91,121,152,182,213,244,274,305,335,365};
  int temp;
  if (a == 1){
    answer = dayname.at((b-1)%7);
  } else{
    temp = monthdays[a-2+ b-1;
    answer = dayname.at(temp%7);
  }
  return answer;
}
int main()
{
    int a=5,b=24;
    //아래는 테스트 출력을 위한 코드입니다.
    cout<<getDayName(a,b);
}
cs

1월 1일이 금요일 -> dayname 배열을 금요일부터 시작
---------------------------------------------------------------------------
5월 24일의 요일 구하기 ( a=5, b=24)
monthdays[a-2] = monthdays[3] : 4월까지의 날짜 합(121)

+ b - 1 (배열의 index가 0부터 시작함)
= 121 + 24 - 1 = 144

144%7 = 4 = dayname.at(4) = "TUE"

=> 5월 24일은 화요일

---------------------------------------------------------------------------
또 다른 예
2월 25일의 요일 구하기 ( a=2, b=25)
monthdays[a-2] = monthdays[0] : 1월까지의 날짜 합(31)

+ b - 1
= 31 + 25 - 1 = 55

55%7 = 6 = dayname.at(6) = "THU"

=> 2월 25일은 목요일

또 다른 풀이
#include<iostream>
#include<string>
using namespace std;
 
string getDayName(int a,int b)
{
    string days[7= {"FRI","SAT","SUN","MON","TUE","WED","THU"};
    int months[13= {31,29,31,30,31,30,31,31,30,31,30,31};
    int cnt = 0;
    
    for(int i =0; i < a-1;i++){
        cnt+= months[i];
    }
    cnt+=b-1;
    return days[cnt%7];
}
int main()
{
    int a=5,b=24;
 
    //아래는 테스트 출력을 위한 코드입니다.
    cout<< getDayName(a,b);
}
 
cs


댓글

가장 많이 본 글