Techy
Techy

Reputation: 35

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.

Upvotes: 0

Views: 631

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

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.

Upvotes: 3

qwn
qwn

Reputation: 367

12 Am translates to 00:00:00 you return as soon as you check for AM you also need to check if it's 12

Upvotes: 1

Related Questions