문자열 형식으로 주어지는 시간을 초단위로 바꾸는 발상을 하는 데에 오래 걸렸지만 그 발상을 하고 나서 구현하는 것은 어렵지 않았다.
기본적인 자바 메소드를 다룰 수 있으면 풀 수 있는 문제였다.
class Solution {
public String solution(String video_len, String pos, String op_start, String op_end, String[] commands) {
// 연산하기 편하게 초 단위 int로 변경
int intVideoLen = stringToSec(video_len);
int intPos = stringToSec(pos);
int intOpStart = stringToSec(op_start);
int intOpEnd = stringToSec(op_end);
// 시작위치가 op 진행 중에 있으면 위치 end로 변경
if(intPos >= intOpStart && intPos <= intOpEnd) intPos = intOpEnd;
// commands 배열 길이만큼 반복문 돌며 명령 수행
for(int i = 0; i < commands.length; i++) {
String command = commands[i];
if(command.equals("prev")) {
intPos-=10;
// 뒤로 감았는데 0보다 작아지면 0으로 초기화
if(intPos < 0) intPos = 0;
// 이동했는데 op 진행 중에 있으면 위치 end로 변경
if(intPos >= intOpStart && intPos <= intOpEnd) intPos = intOpEnd;
} else {
intPos+=10;
// 앞으로 넘겼는데 동영상 길이를 초과하면 동영상 끝으로 초기화
if(intPos > intVideoLen) intPos = intVideoLen;
// 이동했는데 op 진행 중에 있으면 위치 end로 변경
if(intPos >= intOpStart && intPos <= intOpEnd) intPos = intOpEnd;
}
}
String answer = secToString(intPos);
return answer;
}
public int stringToSec(String time) {
String[] tmp = time.split(":");
int sec = (Integer.parseInt(tmp[0])*60) + (Integer.parseInt(tmp[1]));
return sec;
}
public String secToString(int time) {
StringBuilder sb = new StringBuilder();
int min = time/60;
int sec = time%60;
String a = String.format("%02d", min);
String b = String.format("%02d", sec);
sb.append(a).append(":").append(b);
String tmp = sb.toString();
return tmp;
}
}'프로그래머스 1단계' 카테고리의 다른 글
| 프로그래머스 [이웃한 칸] (0) | 2026.03.02 |
|---|---|
| 프로그래머스 [붕대 감기] (0) | 2026.03.01 |
| 프로그래머스 [택배 기사] (0) | 2026.02.28 |
| 프로그래머스 코테 연습 [유연근무제] (0) | 2026.02.27 |