Given a time in 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.
Input Format
A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12.
Output Format
Convert and print the given time in 24-hour format, where 00≤hh≤23.
Sample Input
07:05:45PM
Sample Output
19:05:45
这么简单的题目,居然一直过不了, 这是自己写的代码:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char* time = (char *)malloc(10240 * sizeof(char));
scanf("%s",time);
if(time[strlen(time) - 2] == 'A')
for(int i = 0; i < strlen(time) - 2; i++)
printf("%c", time[i]);
else{
char hour[3];
if(time[0] != '0')
for(int i = 0; i < 2; i++)
hour[i] = time[i];
else hour[0] = time[1];
hour[2] = '\0';
int num = atoi(hour);
num += 12;
if(num == 24){
time[0] = '0';
time[1] = '0';
}
else{
sprintf(hour, "%d", num);
for(int i = 0; i < 2; i++)
time[i] = hour[i];
}
for(int i = 0; i < strlen(time) - 2; i++)
printf("%c", time[i]);
}
return 0;
}
这是正确代码:(被自己蠢哭。。)
#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'); //remember this method
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') //mess up this difference
hh=0;
printf("%02d:%02d:%02d\n",hh,mm,ss);
return 0;
}