简体   繁体   English

12小时AM / PM格式转换为军事(24小时)时间

[英]12-hour AM/PM format to military (24-hour) time

I am trying to solve this task on hackerrank but having problem when submitting solution. 我正在尝试在hackerrank上解决此任务,但是在提交解决方案时遇到了问题。

Here is my solution, I would like to someone point me to mistakes, or give me advice what to avoid when working with strings? 这是我的解决方案,我希望有人指出我的错误,或者给我一些建议,在使用字符串时应避免什么?

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

char clkType[3];
char hours[3];

char* timeConversion(char* s)
{
    strncpy(clkType, &s[8], 2);
    clkType[2] = '\0';

    if(strcmp(clkType, "AM") == 0)
    {
        s[8] = '\0';
        return s;
    }
    else
    {    
        s[0] += 0x1;
        s[1] += 0x2;
        s[8] = '\0';

        strncpy(hours, &s[0], 2);
        hours[2] = '\0';

        if(strcmp(hours, "24") == 0) 
        {
            s[0] = '0';
            s[1] = '0';
            s[8] = '\0';   
        }

        return s;
    }
}

int main() {
    char* s = (char *)malloc(512000 * sizeof(char));
    scanf("%s", s);
    int result_size;
    char* result = timeConversion(s);
    printf("%s\n", result);
    return 0;
}

I am getting expected result when I'm testing it with these 04:59:59AM, 12:40:22AM, 12:45:54PM, 12:00:00AM time cases but when submitting results it gives me errors on those test cases. 在这些04:59:59 AM、12:40:22AM、12:45:54PM、12:00:00AM时间案例中进行测试时,我得到了预期的结果,但是在提交结果时,这些测试案例给了我错误。

You have special handling for midnight. 您在午夜有特殊处理。 You need special handling for noon as well, and you need to fix midnight handling, too. 您还需要在中午进行特殊处理,并且还需要修复午夜处理。

By convention, 12 AM denotes midnight and 12 PM denotes noon. 按照惯例,中午12点表示午夜,中午12点表示中午。 Your code does it the other way around, converting 12:00:00 AM to 12:00:00 (noon) and 12:00:00 PM to midnight. 您的代码以相反的方式进行操作,将12:00:00 AM转换为12:00:00(中午),并将12:00:00 PM转换为午夜。

One simple way of dealing with time conversion problems is to convert the input to a number of seconds from midnight, and then format this number as the desired output. 解决时间转换问题的一种简单方法是将输入转换为午夜后的秒数,然后将该数字格式化为所需的输出。 This approach eliminates character manipulation (adding 12 one digit at a time) and make the code more readable in general. 这种方法消除了字符操作(一次添加12个数字),并使代码通常更具可读性。

12 AM转换为00:00:00 ,您检查AM立即返回,还需要检查是否为12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM