12小时AM / PM格式到军事(24小时)时间

时间:2017-10-11 11:11:04

标签: c arrays string 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,上午12:40:22,下午12:45:54,上午12:00:00测试时,我得到了预期的结果但是在提交结果时它给了我错误那些测试用例。

2 个答案:

答案 0 :(得分:3)

你有午夜的特殊处理。中午也需要特殊处理,你也需要修理午夜处理。

按照惯例,上午12点表示午夜,12点表示中午。您的代码以相反的方式执行,转换为上午12:00:00至中午12:00(中午)和中午12:00:00至午夜。

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

答案 1 :(得分:1)

12 Am会在您检查00:00:00后立即转换为AM,您还需要检查它是否为12