我试图在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:22 am、12:45:54 pm、12:00:00 am时间案例测试它时,我得到了预期的结果,但是当提交结果时,它给了我这些测试案例上的错误。

最佳答案

你在午夜有特别安排。中午也需要特别处理,午夜也需要处理。
按照惯例,上午12点表示午夜,下午12点表示中午。你的代码则相反,将12:00:00 AM转换为12:00:00(中午),12:00:00 PM转换为午夜。
处理时间转换问题的一个简单方法是将输入转换为午夜的秒数,然后将该秒数格式化为所需的输出。这种方法消除了字符操作(一次添加12个一位数),使代码更具可读性。

关于c - 12小时AM/PM格式转换为军事(24小时)时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46686748/

10-12 00:25
查看更多