자라나라 개발머리

[백준 알고리즘/Java11] 조건문 2525 오븐 시계 본문

알고리즘/백준 알고리즘

[백준 알고리즘/Java11] 조건문 2525 오븐 시계

iammindy 2022. 7. 9. 18:40

https://www.acmicpc.net/problem/252

 

2525번: 오븐 시계

첫째 줄에 종료되는 시각의 시와 분을 공백을 사이에 두고 출력한다. (단, 시는 0부터 23까지의 정수, 분은 0부터 59까지의 정수이다. 디지털 시계는 23시 59분에서 1분이 지나면 0시 0분이 된다.)

www.acmicpc.net

 

첫 작성 코드(오답)

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		Scanner s = new Scanner(System.in);
		
		int th = s.nextInt();
		int tm = s.nextInt();
		int m = s.nextInt();
		
		th += m/60;
		tm += m%60;
		
		if(tm>=60) {
			tm -=60; th++;
			
			if(th>=24) th -= 24; //오답 부분
		}
		
		System.out.println(th+" "+tm);
		
		
	}
}

오답 이유:

오답 줄 부분 코드를 if문 밖으로 빼냈어야 함.

위 코드로 작성시 tm이 60을 넘지 않으면 th가 24이상이라도 그대로 출력됨.

ex) 현재시간 23:10 , 걸리는 시간 90분으로 설정했을 경우 25:40으로 출력됨

 

최종 코드

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		Scanner s = new Scanner(System.in);
		
		int th = s.nextInt(); //현재 시간
		int tm = s.nextInt(); //현재 분
		int m = s.nextInt(); //걸리는 시간(분단위)
		
		//시간 단위로 환산 후 현재 시간에 더 함
		th += m/60; 
		tm += m%60;
		
		if(tm>=60) { tm -=60; th++; } //분단위 초과 시 시간단위 ++ 
		if(th>=24) th -= 24; //시간단위 24시간 넘을 경우 -24
		
		System.out.println(th+" "+tm);
		
		
	}
}