프로그래머스 1단계

프로그래머스 [동영상 재생기]

dev-lee 2026. 2. 28. 22:52

문자열 형식으로 주어지는 시간을 초단위로 바꾸는 발상을 하는 데에 오래 걸렸지만 그 발상을 하고 나서 구현하는 것은 어렵지 않았다.

기본적인 자바 메소드를 다룰 수 있으면 풀 수 있는 문제였다.

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;

	}
}