{ }codelper
ternary operatorreading n linesP0422

Switching between AM/PM and 24-hour times

There are two ways to write a time of day: 24-hour notation and 12-hour notation.
24-hour notation has the form "HH:MM".
The hour HH (00 to 23) and the minute MM (00 to 59) are both written with two digits, with a leading 0 for a one-digit number (e.g.
07:05, 19:30).
12-hour notation has the form "h:MM AM" or "h:MM PM".
The hour h (1 to 12) has no leading 0, the minute MM has two digits, and after the minute comes one space and then AM or PM (e.g.
7:05 AM, 10:30 PM).
In 24-hour notation, 00:00 to 11:59 are AM, and 12:00 to 23:59 are PM.
The 12-hour hour h is the remainder of the 24-hour hour divided by 12, and it is 12 when that remainder is 0.
So 00:30 is 12:30 AM, 12:00 is 12:00 PM, and 13:05 is 1:05 PM.
The minute is the same in both notations.
The first line gives the number of times n.
Each of the next n lines gives one time.
Each line may be in 24-hour notation or in 12-hour notation.
Convert a time given in 24-hour notation to 12-hour notation, and a time given in 12-hour notation to 24-hour notation.
Print the converted times in input order, one per line.

Input
1 ≤ n ≤ 3,000.
Each line is in exactly one of the two forms above, with no other spaces at the start or end of the line.
AM and PM are written in uppercase English letters.
Output
n lines: one converted time per line
Example 1 · stdin
6
00:30
12:00
23:59
7:05 PM
12:15 AM
12:40 PM
stdout
12:30 AM
12:00 PM
11:59 PM
19:05
00:15
12:40
Example 2 · stdin
3
09:07
11:59 AM
1:00 AM
stdout
9:07 AM
11:59
01:00
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

This problem takes all 8 languages.
Converting the hour means picking one of two values by one condition, so a ternary operator writes it in one line.
24-hour → 12-hour is h % 12 == 0 ? 12 : h % 12 and h < 12 ? "AM" : "PM"; 12-hour → 24-hour is h % 12 + (pm ? 12 : 0).
C, C++, Java, C#, JS, TS and Craykon use the order condition ? value if true : value if false; only Python puts the true value before the condition, as in 12 if h % 12 == 0 else h % 12.
Trap one: with h % 12 alone, hour 0 becomes 0, so 00:30 in example 1 prints as 0:30 AM and 12:00 as 0:00 PM.
Trap two: PM starts at 12.
Writing h <= 12 ? "AM" : "PM" turns 12:00 in example 1 into 12:00 AM.
Trap three: in 12-hour → 24-hour, just adding 12 for PM (pm ? h + 12 : h) turns 12:15 AM in example 1 into 12:15 and 12:40 PM into 24:40.
First turn 12 into 0 with h % 12, AM or PM, and then add 12 for PM.
Trap four: the 24-hour hour has two digits.
Writing it with C printf("%d:%s") turns 1:00 AM in example 2 into 1:00.
Pad it with C %02d, C++ std::setw(2) << std::setfill('0'), Java String.format("%02d", h), C# $"{h:00}", Python f"{h:02d}", JS and TS String(h).padStart(2, "0"), Craykon ("" + h).PadLeft(2, "0").
Trap five: the ternary operator binds after +.
In JS, h12 + ":" + mm + " " + h < 12 ? "AM" : "PM" is read as (h12 + ":" + mm + " " + h) < 12 ? "AM" : "PM".
The string on the left, "12:30 0", becomes NaN as a number, so the comparison is always false, and the three 24-hour lines of example 1 all print as the single word PM.
In Python, str(h12) + ":" + mm + " " + "AM" if h < 12 else "PM" is read as (… + "AM") if h < 12 else "PM", so a PM line (12:00 and 23:59 in example 1) prints only PM.
Java, C# and TS cannot compare a string with a number using <, so they give a compile error (in TS the type error TS2365), and Craykon stops while running with an error saying < compares only numbers with numbers or strings with strings.
So store the chosen value in a variable first, or wrap the ternary in parentheses.
Trap six: lines have different numbers of words.
A 12-hour line such as 7:05 PM has two words.
Reading one time as one word with C++ std::cin >> s or C scanf("%s") reads PM as the next time (in example 1, 7:05 prints as 7:05 AM, and then std::stoi("PM") throws).
Read whole lines: Python input(), JS and TS read everything and split("\n"), Java readLine(), C# Console.ReadLine(), C fgets, C++ std::getline, Craykon Console.ReadLine().

Pythonmain.py · 14 lines
n = int(input())for _ in range(n):    parts = input().split()    hh, mm = parts[0].split(":")    h = int(hh)    if len(parts) == 1:        # 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다        h12 = 12 if h % 12 == 0 else h % 12        ampm = "AM" if h < 12 else "PM"        print(f"{h12}:{mm} {ampm}")    else:        # 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다        h24 = h % 12 + (12 if parts[1] == "PM" else 0)        print(f"{h24:02d}:{mm}")
JavaScriptmain.js · 19 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const out = [];for (let i = 1; i <= n; i++) {  const parts = lines[i].trim().split(" ");  const [hh, mm] = parts[0].split(":");  const h = Number(hh);  if (parts.length === 1) {    // 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다    const h12 = h % 12 === 0 ? 12 : h % 12;    const ampm = h < 12 ? "AM" : "PM";    out.push(`${h12}:${mm} ${ampm}`);  } else {    // 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다    const h24 = (h % 12) + (parts[1] === "PM" ? 12 : 0);    out.push(`${String(h24).padStart(2, "0")}:${mm}`);  }}console.log(out.join("\n"));
TypeScriptmain.ts · 20 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const out: string[] = [];for (let i = 1; i <= n; i++) {  const parts: string[] = lines[i].trim().split(" ");  const [hh, mm] = parts[0].split(":");  const h: number = Number(hh);  if (parts.length === 1) {    // 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다    const h12: number = h % 12 === 0 ? 12 : h % 12;    const ampm: string = h < 12 ? "AM" : "PM";    out.push(`${h12}:${mm} ${ampm}`);  } else {    // 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다    const h24: number = (h % 12) + (parts[1] === "PM" ? 12 : 0);    out.push(`${String(h24).padStart(2, "0")}:${mm}`);  }}console.log(out.join("\n"));
JavaMain.java · 28 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(br.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            String[] parts = br.readLine().trim().split(" ");            String[] hm = parts[0].split(":");            int h = Integer.parseInt(hm[0]);            String mm = hm[1];            if (parts.length == 1) {                // 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다                int h12 = h % 12 == 0 ? 12 : h % 12;                String ampm = h < 12 ? "AM" : "PM";                out.append(h12).append(':').append(mm).append(' ').append(ampm).append('\n');            } else {                // 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다                int h24 = h % 12 + (parts[1].equals("PM") ? 12 : 0);                out.append(String.format("%02d", h24)).append(':').append(mm).append('\n');            }        }        System.out.print(out);    }}
C#Main.cs · 32 lines
using System;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var sb = new StringBuilder();        for (int i = 0; i < n; i++)        {            string[] parts = Console.ReadLine().Trim().Split(' ');            string[] hm = parts[0].Split(':');            int h = int.Parse(hm[0]);            string mm = hm[1];            if (parts.Length == 1)            {                // 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다                int h12 = h % 12 == 0 ? 12 : h % 12;                string ampm = h < 12 ? "AM" : "PM";                sb.Append($"{h12}:{mm} {ampm}\n");            }            else            {                // 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다                int h24 = h % 12 + (parts[1] == "PM" ? 12 : 0);                sb.Append($"{h24:00}:{mm}\n");            }        }        Console.Write(sb);    }}
C++main.cpp · 29 lines
#include <iomanip>#include <iostream>#include <sstream>#include <string> int main() {    std::string line;    std::getline(std::cin, line);    int n = std::stoi(line);    for (int i = 0; i < n; i++) {        // 12시간 표기 줄은 "7:05 PM"처럼 두 낱말이라 한 줄을 통째로 읽는다        std::getline(std::cin, line);        std::istringstream in(line);        std::string time, ampm;        in >> time >> ampm;        std::size_t colon = time.find(':');        int h = std::stoi(time.substr(0, colon));        std::string mm = time.substr(colon + 1);        if (ampm.empty()) {            // 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다            int h12 = h % 12 == 0 ? 12 : h % 12;            std::cout << h12 << ':' << mm << ' ' << (h < 12 ? "AM" : "PM") << '\n';        } else {            // 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다            int h24 = h % 12 + (ampm == "PM" ? 12 : 0);            std::cout << std::setw(2) << std::setfill('0') << h24 << ':' << mm << '\n';        }    }}
Cmain.c · 26 lines
#include <stdio.h>#include <string.h> int main(void) {    char line[64];    int n;    if (fgets(line, sizeof line, stdin) == NULL) return 0;    sscanf(line, "%d", &n);    for (int i = 0; i < n; i++) {        /* 12시간 표기 줄은 "7:05 PM"처럼 두 낱말이라 한 줄을 통째로 읽는다 */        fgets(line, sizeof line, stdin);        int h;        char mm[3], ampm[3];        int got = sscanf(line, "%d:%2s %2s", &h, mm, ampm);        if (got == 2) {            /* 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다 */            int h12 = h % 12 == 0 ? 12 : h % 12;            printf("%d:%s %s\n", h12, mm, h < 12 ? "AM" : "PM");        } else {            /* 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다 */            int h24 = h % 12 + (strcmp(ampm, "PM") == 0 ? 12 : 0);            printf("%02d:%s\n", h24, mm);        }    }    return 0;}
Craykonmain.cray · 21 lines
n = Console.ReadLine().ToNumber();for (i = 0; i < n; i++){    칸 = Console.ReadLine().Trim().Split(" ");    시분 = 칸[0].Split(":");    h = 시분[0].ToNumber();    mm = 시분[1];    if (칸.Count == 1)    {        // 24시간 → 12시간: 나머지가 0인 0시·12시는 12로 쓴다        h12 = h % 12 == 0 ? 12 : h % 12;        ampm = h < 12 ? "AM" : "PM";        Console.WriteLine(h12 + ":" + mm + " " + ampm);    }    else    {        // 12시간 → 24시간: 12시를 먼저 0으로 바꾼 뒤 PM이면 12를 더한다        h24 = h % 12 + (칸[1] == "PM" ? 12 : 0);        Console.WriteLine(("" + h24).PadLeft(2, "0") + ":" + mm);    }}