Time Convertion

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值