Time Conversion Solution | Hackerrank Solutions | Using C/C++ by Code4xU

 


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

Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.

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):

  • s: a string representing time in 12-hour format

Input Format

A single string s containing a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01 < hh < 12 and 00 < mm,ss < 59.

Constraints

  • All input times are valid

Output Format

Convert and print the given time in 24-hour format, where 00 < hh < 23.

Sample Input 0

  07:05:45PM

Sample Output 0

  19:05:45

Solution:

Code in C

#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { char s[20]; scanf("%s",s); if(s[strlen(s)-2]=='P' || s[strlen(s)-2]=='p') { if(!(s[0]=='1' && s[1]=='2')) { s[0]=s[0]+1; s[1]=s[1]+2; } } else if(s[strlen(s)-2]=='A' || s[strlen(s)-2]=='a') { if(s[0]=='1' && s[1]=='2') { s[0]='0'; s[1]='0'; } } s[strlen(s)-2]='\0'; printf("%s",s); return 0; }

Code in C++ 

#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { string s; string h; int hr; cin>>s; hr = ((s[0]-'0')*10)+(s[1]-'0'); if(s[8]=='P'&&s[9]=='M'&& hr ==12) cout<<to_string(hr); else if(s[8]=='P'&&s[9]=='M') cout<<to_string(hr+12); else if(s[8]=='A'&&s[9]=='M'&&hr==12) cout<<"00"; else cout<< s[0]<<s[1]; for(int i =2;i<8;i++) cout<<s[i]; cout <<endl; return 0; }

 

Sajal Gupta

Hi, i am sajal.I am a hardworking engineering graduate specialised in Computer Science Engineering ... Along with my degree, I completed C/C++,.Net,Java and SQL courses From Youtube and Other sources and various technologies.I learnt helped me develop my final year project called Code4xU..

Post a Comment