알고리즘 문제풀이/백준

#2884 : 알람 시계

모항 2023. 3. 8. 16:22

풀이방법

사용된 것:

수학

사칙연산

 

 

 

 

 

2022.03.15

이전에 풀었던 문제인데 블로그에 풀이를 적지 않았어서, 지금 남긴다.

 

덧셈과 뺄셈만 해주면 된다.

 

일단 주어진 분 값에서 45를 뺀다.

 

45를 뺐더니 0보다 작아졌다면, 시 값에서 1을 빼고 분 값에는 60을 더하여 올바른 시간 표기로 바꾸어준다.

 

그런데 주어진 시 값이 원래 0이었다면 위의 과정에서 시 값이 -1이 되어버린다.

따라서, 시 값이 음수일 경우 시 값에 24를 더해주는 작업을 해준다.

 

시 값과 분 값을 화면에 출력하면 문제가 해결된다.

 

 

 

코드

Java(2022.03.15)

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		//입력값 읽어오기		
		int h = sc.nextInt();
		int m = sc.nextInt();
		
		//분 값에서 45를 빼주기
		m -= 45;
        
		//뺄셈 결과 시, 분 값이 음수가 되었을 경우 올바른 시간 표시로 바꾸어주기
		if(m<0) {
			h--; m += 60;
		}
		if(h<0) h = 24+h;

		//정답 출력
		System.out.print(h + " " + m);
		
		sc.close();
	}

}

 

▼EFUB 스터디 제출용 함수형 답안 (2023.03.08)

더보기
package onboard;

import java.util.ArrayList;
import java.util.List;

public class Problem1 {
    public static List<Integer> solution(Integer hour, Integer minute){
        List<Integer> answer = new ArrayList<>();

        //subtract 45 from the minute value
        minute -= 45;

        //if the minute value became less than zero after the subtraction,
        //add 60 to it and subtract 1 from the hour value
        if(minute<0) {
            hour--; minute += 60;
        }
        //if the hour value became less than 0, add 24 to it
        if(hour<0) hour = 24+hour;

        //add the values to the answer list
        answer.add(hour);
        answer.add(minute);

        //return answer
        return answer;
    }
}

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

#2587 : 대표값2  (0) 2023.03.12
#10804 : 카드 역배치  (0) 2023.03.12
#5585 : 거스름돈  (0) 2023.01.19
#1049 : 기타줄  (0) 2023.01.18
#15649 : N과 M (1)  (0) 2023.01.18