Recent CP News

Time Conversion || Easy Problem

Let’s do a Time Conversion

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note: Midnight is12:00;00AM  on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and  12:00:00 on a 24-hour clock.

Input Format

A single string containing a time in 12-hour clock format (i.e. hh:mm:ss AM or hh:mm:ss PM),where 01<=hh<=12 and 00<=mm,ss<=59.

Output Format

Convert and print the given time in 24-hour format, where 00<=hh<=23.

Sample Input

07:05:45PM

Output Format

19:05:45

Solution with Explanation

We only need to change the hours to convert the time from an AM/PM format to 24 hour format. We need to add +12 to the hours if the time is in PM. We need to take care of 12:mm:ssAM types additionally as 12:mm:ssAM in a 24 hour format is 00:mm:ss. 12:mm:ssPM type values in 24 hour format are in the form 12:mm:ss.

Time Complexity:O(1)

Featured Solutions

C++

#include<iostream>
#include<cstdio>

using namespace std;

int main() {
    string s;
    cin >> s;

    int n = s.length();
    int hh, mm, ss;
    hh = (s[0] - '0') * 10 + (s[1] - '0');
    mm = (s[3] - '0') * 10 + (s[4] - '0');
    ss = (s[6] - '0') * 10 + (s[7] - '0');

    if (hh < 12 && s[8] == 'P') hh += 12;
    if (hh == 12 && s[8] == 'A') hh = 0;

    printf("%02d:%02d:%02d\n", hh, mm, ss);

    return 0;
}

Python

s = raw_input()
zn = s[-2:]
if zn == "PM" and s[:2] != "12":
    s = str(12 + int(s[:2])) + s[2:]
if zn == "AM" and s[:2] == "12":
    s = "00" + s[2:]
print s[:-2]

Perl

use strict;
use warnings;

my $time1=<>;
chomp($time1);
my @h=split(':',$time1);
if(($time1 =~ /AM$/) && ($h[0] ==12)){
$h[0]=0;
}
if(($time1 =~ /PM$/) && ($h[0] !=12)){
    $h[0]+=12;
}
$h[0]="0$h[0]" if(length($h[0])==1);
$time1 =~ s/(\d+):/$h[0]:/;
$time1 =~ s/[A|P]M//;
print $time1;

Ruby

def parse_time(time)
    hours,minutes,seconds,modifier = time.delete(":").scan(/\w{2}/)
    [correct_hours(hours,modifier),minutes,seconds].join(':')
end
def correct_hours(hours,modifier)
    if modifier == "PM" && hours.to_i != 12 
        (hours.to_i + 12)
    elsif hours.to_i == 12 and modifier == "AM"
        hours = "00"
    else
        hours
    end
end

puts parse_time(gets.chomp)

{Code with Code@ter}

Give Your Reviews




Leave a Reply