繁体   English   中英

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

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

我正在尝试在hackerrank上解决此任务,但是在提交解决方案时遇到了问题。

这是我的解决方案,我希望有人指出我的错误,或者给我一些建议,在使用字符串时应避免什么?

#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;
}

在这些04:59:59 AM、12:40:22AM、12:45:54PM、12:00:00AM时间案例中进行测试时,我得到了预期的结果,但是在提交结果时,这些测试案例给了我错误。

您在午夜有特殊处理。 您还需要在中午进行特殊处理,并且还需要修复午夜处理。

按照惯例,中午12点表示午夜,中午12点表示中午。 您的代码以相反的方式进行操作,将12:00:00 AM转换为12:00:00(中午),并将12:00:00 PM转换为午夜。

解决时间转换问题的一种简单方法是将输入转换为午夜后的秒数,然后将该数字格式化为所需的输出。 这种方法消除了字符操作(一次添加12个数字),并使代码通常更具可读性。

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

暂无
暂无

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

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