https://www.acmicpc.net/problem/1408
ch, cm, cs = map(int, input().split(":"))
sh, sm, ss = map(int, input().split(":"))
sh += 24
lh = sh - ch
lm = sm - cm
ls = ss - cs
print(f"{lh}:{lm}:{ls}")
일단 여기까지는 짤 수 있었다.
근데 문제는... 이렇게 해서 실행해보면
이렇게 음수 시간이 출력된다. 이 음수 시간을 어떻게 처리할 것인가가 이 문제의 핵심이다.
그래서 내가 생각한 해결방법은
현재시간 + 24시간 - 시작시간 = 남은 시간
공식을 이용하는 것이다. 일단 저대로 더하고, 분과 초에서 음수가 나온다면 각각 60을 더해준 뒤 시, 분에서 1을 빼주는 것이다!
ch, cm, cs = map(int, input().split(":"))
sh, sm, ss = map(int, input().split(":"))
lh = sh - ch
lm = sm - cm
ls = ss - cs
if ls < 0:
ls += 60
lm -= 1
if lm < 0:
lm += 60
lh -= 1
if lh < 0:
lh += 24
print(f"{lh:02}:{lm:02}:{ls:02}")
찾아보니까 모든 시간 단위를 초로 바꾸어 계산한 후, 다시 60으로 계속 나누어 정답을 구한 풀이가 대부분이었다. 이 방식으로도 코드를 작성해보았다.
ch, cm, cs = map(int, input().split(":"))
sh, sm, ss = map(int, input().split(":"))
time = (sh * 3600) + (sm * 60) + (ss - (ch * 3600 + cm * 60 + cs))
if time < 0:
time += 24 * 3600
lh = time // 3600
lm = (time % 3600) // 60
ls = time % 60
print(f"{lh:02}:{lm:02}:{ls:02}")