Hello coders, today we are going to solve Time Conversion HackerRank Solution which is a Part of HackerRank Algorithm Series.

Task
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: – 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
– 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
Example
- s = ’12:01:00PM’
Return ’12:01:00′. - s = ’12:01:00AM’
Return ’00:01:00′.
Function Description
Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.
timeConversion has the following parameter(s):
- string s: a time in 12 hour format
Returns
- string: the time in 24 hour format
Input Format
A single string s that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM).
Constraints
- All input times are valid
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
Solution – Time Conversion
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
import os import sys def timeConversion(s): time = s.split(":") if s[-2:] == "PM": if time[0] != "12": time[0] = str(int(time[0])+12) else: if time[0] == "12": time[0] = "00" ntime = ':'.join(time) return str(ntime[:-2]) if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = timeConversion(s) f.write(result + '\n') f.close()
Disclaimer: The above Problem (Time Conversion) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.