문제 위치 : https://school.programmers.co.kr/learn/courses/30/lessons/340213?language=cpp#
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
처음으로 풀어본 프로그래머스 문제이다.
LV1은 간단하다고 해서 짧게 걸릴 줄 알았는데 백준과는 다르게 생긴 모습에 다소 시간이 더 걸렷던 것 같다.
이번 문제는 구현을 목표로 하는 문자열 문제이다.
구현 내용은 어려운 것은 아니지만 문제를 해결하는데 있어 문자열을 정수형으로 치환하고 이를 계산하여 다시 문자열의 양식을 지켜 출력해주어야 한다.
시간 위치를 비교함으로 연산해야하므로 문자열을 숫자로 처리하고 숫자를 문자열로 치환하는 함수를 만들어 문제를 해겷하였다.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 시간 계산 보조 함수: "mm:ss"를 초 단위로 변환
int timeToSeconds(const string& time_str) {
int minutes = stoi(time_str.substr(0, 2));
int seconds = stoi(time_str.substr(3, 2));
return minutes * 60 + seconds;
}
// 초 단위를 "mm:ss" 형식으로 변환
string secondsToTime(int total_seconds) {
int minutes = total_seconds / 60;
int seconds = total_seconds % 60;
return (minutes < 10 ? "0" : "") + to_string(minutes) + ":" + (seconds < 10 ? "0" : "") + to_string(seconds);
}
string solution(string video_len, string pos, string op_start, string op_end, vector<string> commands) {
// 각 시간 정보들을 초 단위로 변환
int video_length = timeToSeconds(video_len);
int current_pos = timeToSeconds(pos);
int opening_start = timeToSeconds(op_start);
int opening_end = timeToSeconds(op_end);
// 명령어 처리
for (const string& cmd : commands) {
if (opening_start <= current_pos && current_pos <= opening_end) {
current_pos = opening_end;
}
if (cmd == "next") {
current_pos += 10; // 10초 후로 이동
if (current_pos > video_length) { // 비디오 길이를 넘으면 마지막으로 이동
current_pos = video_length;
}
}
else if (cmd == "prev") {
current_pos -= 10; // 10초 전으로 이동
if (current_pos < 0) { // 0초 아래로 내려가면 처음으로 이동
current_pos = 0;
}
}
// 만약 10초 미만이면 0초로 이동
if (current_pos < 10) {
current_pos = 0;
}
if (opening_start <= current_pos && current_pos <= opening_end) {
current_pos = opening_end;
}
}
// 최종 시간을 "mm:ss" 형식으로 변환하여 반환
return secondsToTime(current_pos);
}
int main() {
string video_len, pos, op_start, op_end, tmp;
vector<string> commands;
// 입력 받기
cin >> video_len >> pos >> op_start >> op_end;
// 명령어 입력 받기
while (cin >> tmp) {
commands.push_back(tmp);
}
// solution 함수 호출 및 결과 출력
string result = solution(video_len, pos, op_start, op_end, commands);
cout << result << endl;
return 0;
}
'문제 풀이 > 문제 풀이(프로그래머스)' 카테고리의 다른 글
Summer/Winter Coding(~2018)소수 만들기 (0) | 2024.10.25 |
---|---|
Summer/Winter Coding(~2018) 영어 끝말잇기 (0) | 2024.10.25 |
[PCCE 기출문제] 10번 / 공원 (0) | 2024.10.25 |
[PCCE 기출문제] 9번 / 지폐 접기 (0) | 2024.10.24 |
[PCCP 기출문제] 2번 / 퍼즐 게임 챌린지 (3) | 2024.10.21 |