작성일 :

문제 링크

15080번 - Every Second Counts

설명

시작 시각과 종료 시각이 주어질 때 경과 시간을 초 단위로 구하는 문제입니다.


접근법

각 시각을 초로 환산하여 차이를 구합니다.

종료 시각이 시작 시각보다 작으면 자정을 넘긴 것이므로 24시간을 더해 보정합니다.



Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;

class Program {
  static int ToSeconds(string time) {
    var parts = time.Split(' ');
    var h = int.Parse(parts[0]);
    var m = int.Parse(parts[2]);
    var s = int.Parse(parts[4]);
    return h * 3600 + m * 60 + s;
  }

  static void Main() {
    var start = ToSeconds(Console.ReadLine()!);
    var end = ToSeconds(Console.ReadLine()!);
    var diff = end - start;
    if (diff < 0) diff += 24 * 3600;
    Console.WriteLine(diff);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;

int toSeconds() {
  int h, m, s; char colon;
  cin >> h >> colon >> m >> colon >> s;
  return h * 3600 + m * 60 + s;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int start = toSeconds();
  int end = toSeconds();
  int diff = end - start;
  if (diff < 0) diff += 24 * 3600;
  cout << diff << "\n";

  return 0;
}