简体   繁体   中英

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.

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.

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. 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.

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 AM转换为00:00:00 ,您检查AM立即返回,还需要检查是否为12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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