Time conversion Hackerrank solution in C , Cpp , Python 3 and Java
Problem Statement : 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.
Example
s = 12:01:00PM
- 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 hour format
Returns
- string: the time in hour format
Input Format
A single string that represents a time in -hour clock format (i.e.: or ).
Constraints
- All input times are valid
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
Solution :
Code in C :
#include<stdio.h>#include<string.h>
int main (){ char t1[10]; scanf("%s",t1); int hr,mn,sec; hr= (t1[0]-'0')*10 + (t1[1]-'0'); mn= (t1[3]-'0')*10+(t1[4]-'0'); sec=(t1[6]-'0')*10+(t1[7]-'0'); if (t1[8]=='A'&& hr==12 ) { hr=00; } else if ( t1[8]=='P') { if ( hr==12 ) { hr=12; } else { hr=hr+12; }}
printf("%02d:%02d:%02d",hr,mn,sec); }
Code in C++:
#include<iostream>#include<string>#include<cstring>using namespace std ;int main (){ string t1; cin>>t1; int hr,mn,sec; hr= (t1[0]-'0')*10 + (t1[1]-'0'); mn= (t1[3]-'0')*10+(t1[4]-'0'); sec=(t1[6]-'0')*10+(t1[7]-'0'); if (t1[8]=='A'&& hr==12 ) { hr=00; } else if ( t1[8]=='P') { if ( hr==12 ) { hr=12; } else { hr=hr+12; }}
printf("%02d:%02d:%02d",hr,mn,sec); }
Code in python :
ins = input().strip()
is_pm = ins[-2:].lower() == 'pm'time_list = list(map(int, ins[:-2].split(':')))
if is_pm and time_list[0] < 12: time_list[0] += 12
if not is_pm and time_list[0] == 12: time_list[0] = 0
print(':'.join(map(lambda x: str(x).rjust(2, '0'), time_list)))
Code in Java :
import java.io.*;import java.util.*;import java.text.*;import java.math.*;import java.util.regex.*;
public class Solution {
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); //07:05:45PM DateFormat inFormat = new SimpleDateFormat( "hh:mm:ssaa"); DateFormat outFormat = new SimpleDateFormat( "HH:mm:ss");
Date date = null; try { date = inFormat.parse(s); }catch (ParseException e ){ e.printStackTrace(); } if( date != null ){ String myDate = outFormat.format(date); System.out.println(myDate); } }
}
Please comment if you have any doubt or for any other problem .
Thanks
0 Comments