[英]Given a time in -hour AM/PM format, convert it to military (24-hour) time
[英]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.