[백준 3029] 경고 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
현재 시각과 특정 시각이 hh:mm:ss
형식으로 주어졌을 때,
두 시각 사이에 정인이가 기다려야 할 시간 차이를 구하는 문제입니다.
두 시각이 같다면 하루 전체를 기다려야 하므로 24:00:00
을 출력해야 하며,
그 외의 경우에는 두 시각의 차이를 hh:mm:ss
형식으로 출력합니다.
접근법
-
현재 시각과 목표 시각을 각각
\[\text{총 초} = \text{시} \times 3600 + \text{분} \times 60 + \text{초}\]시
,분
,초
단위로 나누고,
초 단위로 환산하여 비교합니다: - 두 시각이 같다면
24:00:00
을 출력합니다. - 현재 시각이 더 늦은 경우에는 다음 날로 넘어가야 하므로
86400초(24시간)
에서현재 시각
을 빼고목표 시각
을 더한 값을 사용합니다. - 그렇지 않으면 단순히
목표 시각 - 현재 시각
으로 차이를 구합니다. - 차이 값을 다시 시, 분, 초로 변환한 후 출력 형식에 맞게 출력합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
class Program {
static void Main() {
var ct = Console.ReadLine();
var tt = Console.ReadLine();
var ch = int.Parse(ct.Substring(0, 2));
var cm = int.Parse(ct.Substring(3, 2));
var cs = int.Parse(ct.Substring(6, 2));
var th = int.Parse(tt.Substring(0, 2));
var tm = int.Parse(tt.Substring(3, 2));
var ts = int.Parse(tt.Substring(6, 2));
int sc = ch * 3600 + cm * 60 + cs;
int st = th * 3600 + tm * 60 + ts;
if (sc == st) {
Console.WriteLine("24:00:00");
return;
}
int sw = sc > st ? 86400 - sc + st : st - sc;
int wh = sw / 3600; sw %= 3600;
int wm = sw / 60; sw %= 60;
Console.WriteLine($"{wh:D2}:{wm:D2}:{sw:D2}");
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string ct, tt;
cin >> ct >> tt;
int ch = stoi(ct.substr(0, 2)), cm = stoi(ct.substr(3, 2)), cs = stoi(ct.substr(6, 2));
int th = stoi(tt.substr(0, 2)), tm = stoi(tt.substr(3, 2)), ts = stoi(tt.substr(6, 2));
int sc = ch * 3600 + cm * 60 + cs;
int st = th * 3600 + tm * 60 + ts;
if (sc == st) {
cout << "24:00:00\n";
return 0;
}
int sw = sc > st ? 86400 - sc + st : st - sc;
int wh = sw / 3600; sw %= 3600;
int wm = sw / 60; sw %= 60;
cout << setfill('0') << setw(2) << wh << ":"
<< setw(2) << wm << ":"
<< setw(2) << sw << "\n";
return 0;
}