Time Conversion

Given a time in -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.

input-> A single string  that represents a time in -hour clock format (i.e.:  or ).

Example 1:
s= 12:01:00PM

Output :
 12:01:00

Example 2:

s= 12:01:00AM

Output :
00:01:00


Example 3:

input:
s= 07:05:45PM

Output :
19:05:45




c++ implementation:

string timeConversion(string s) { int n=s.length(); string r; if(s[n-2]=='P') { string s1 = ""; s1=s1+s[0]; string s2 = ""; s2=s2+s[1]; string m=s1+s2; int v=stoi(m); if(v == 12) { for(int i=0;i<n-2;i++) { r=r+s[i]; } } else { v=v+12; m=to_string(v); r=r+m; for(int i=2;i<n-2;i++) { r=r+s[i]; } } } else { string s1 = ""; s1=s1+s[0]; string s2 = ""; s2=s2+s[1]; string m=s1+s2; int v=stoi(m); if(v == 12) { r=r+"00"; for(int i=2;i<n-2;i++) { r=r+s[i]; } } else { for(int i=0;i<n-2;i++) { r=r+s[i]; } } } return r; }


Time Complexity: O(n)
space Complexity: O(1)  

darkmode