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:
- 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))
- 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;
}
- C language
ReplyDeleteGreat Attempt! and Amazingly mention all the things about Time conversion