Time Conversion || Codechef Solution

 

Time Conversion


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

Note: Midnight is  on a -hour clock, and  on a -hour clock. Noon is  on a -hour clock, and  on a -hour clock.

Input Format

A single string containing a time in -hour clock format (i.e.:  or ), where  and .

Output Format

Convert and print the given time in -hour format, where .

  • Solutions:
  1. Python 3.6

def convert24(str1): 

    if str1[-2:] == "AM" and str1[:2] == "12": 

        return "00" + str1[2:-2] 

    elif str1[-2:] == "AM": 

        return str1[:-2]     

    elif str1[-2:] == "PM" and str1[:2] == "12": 

        return str1[:-2]  

    else: 

        return str(int(str1[:2]) + 12) + str1[2:8] 

time = input().strip()

print(convert24(time))

  1. C++

#include <iostream>

#include <iomanip>

using namespace std;


int main() {

    string str;

    cin >> str;

    int hh = stoi(str.substr(0,2));

    int mm = stoi(str.substr(3,2));

    int ss = stoi(str.substr(6,2));

    string d = str.substr(8,2);

    if (d == "AM" && (hh != 12 && mm != 0 & ss != 0)) {

        cout << setfill('0') << setw(2) << hh << ":" << setfill('0') << setw(2) << mm << ":" << setfill('0') << setw(2) << ss;

    }

    else if(d == "PM") {

        cout << setfill('0') << setw(2) << hh+12 << ":" << setfill('0') << setw(2) << mm << ":" << setfill('0') << setw(2) << ss;

    }

    else {

        cout << "00:00:00";

    }

return 0;

}

  1. C language
#include<stdio.h>
#include<stdlib.h>
int main()
{
  int h,m,s;
  char t[2];
  scanf("%d:%d:%d%s",&h,&m,&s,t);
    if(strcmp("PM",t)==0 && h!=12)
    {
      h+=12;
    }
    if(strcmp("AM",t)==0 && h==12)
    {
      h=0;
    }
    printf("%02d:%02d:%02d",h,m,s);
    return 0;
}      

🙏THANKS FOR VISIT🙏


Time Conversion || Codechef Solution Time Conversion || Codechef Solution Reviewed by CodexRitik on November 06, 2020 Rating: 5

1 comment:

Powered by Blogger.