## Tuesday, 18 August 2015

### Time Conversion Hacker Rank Problem Solution Using C++.

/*
Time Conversion

Problem Statement
You are given time in AM/PM format. Convert this into a 24 hour format.
Note Midnight is 12:00:00AM or 00:00:00 and 12 Noon is 12:00:00PM.
Input Format
Input consists of time in the AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM
where
01hh12
00mm59
00ss59
Output Format
You need to print the time in 24 hour format i.e. hh:mm:ss
where
00hh23
00mm59
00ss59
Sample Input
07:05:45PM

Sample Output
19:05:45

TAG: C++,Implementation , Simple Program , Hacker Rank , Algorithm Easy.

*/

Solution:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<cstring>
using namespace std;
/*
*
* Prosen Ghosh
* American International University - Bangladesh (AIUB)
*
*/
int main() {
int h,m,s;
char c[2];
scanf("%d:%d:%d%s",&h,&m,&s,c);
if(!strcmp(c,"PM") && h != 12)h+=12;
if(!strcmp(c,"AM") && h == 12)h = 0;
printf("%02d:%02d:%02d\n",h,m,s);
return 0;
}

1. for this line,printf("%02d:%02d:%02d\n",h,m,s); what is the 02 for?

1. The 0 means to pad the field using zeros and the 2 means that the field is two characters wide, so for any numbers that take less than 2 characters to display, it will be padded with a 0.

2. I didn't get the strcmp line plzz explain it to me

3. so am I what is this strcmp

4. https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

2. How do I do it in C++

1. You can use:
cout << setfill('0') << setw(2) << your_value;

Don't forget to include iomanip :)

2. #include dosent work

3. I hope
char c[2];
is too short
char c[3] = {}; is better.

Try this with clang address sanitizer:

4. The first strcmp statement working isn't clearing explained you must explain it brief in comments.

5. This comment has been removed by the author.

6. #include
#include
#include
#include
#include
#include
#include
using namespace std;

int main(){
string time,temp;
cin >> time;
int pos =0;
pos = time.find(":");
int h = stoi(time.substr(0, pos));

temp = time.substr(pos+1);
pos = temp.find(":");
int m = stoi(temp.substr(0,pos));

int s = stoi(temp.substr(pos+1, 2));

if((string::npos != time.find("PM")) && (h != 12))h+=12;
if((string::npos != time.find("AM")) && (h == 12))h = 0;
cout << setfill('0') << setw(2) << h << ":" << setfill('0') << setw(2)<< m << ":" << setfill('0') << setw(2) << s <<endl;
return 0;
}

7. Can you explain the logic of
If(!strcmp(c,"AM") && h!=12)H=H+12;

1. The code doesn't have that statement.

2. we are comparing c with pm if its pm then strcmp will return 0 but for and case we need 1 so we are using (!)not here.Further if h is suppose 7 then in case of pm we have to make it 19 so we are doing +12 to it.

8. I'm don't understand the code