본문 바로가기

문제풀이/C 문제풀이

[HackerRank]Time Conversion

Time Conversion

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.

Function Description
Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.
Input Format
A single string s containing a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01<=hh<=12 and 00<=mm,ss<=59.
Output Format
Convert and print the given time in 24-hour format, where 00<=hh<=23.

CODE

char* timeConversion(char* s) {
	char full_time[9], h[2];
	char *t[] = { "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" }; //PM일 경우 변환할 시간
	strncpy(full_time, s, 8); // 요소 변환이 쉬운 배열을 사용하기 위하여 문자열 복사
	full_time[8] = NULL; // 문자열 끝에 NULL
	if (*(s + 8) == 'P') { // PM이라면
		strncpy(h, s, 2); // 시간에 해당하는 내용 복사
		strncpy(full_time, t[atoi(h) - 1], 2); // 문자열 h을 정수로 바꿔서 24-hour로 변환하고 우리가 출력할 문자열에 붙여넣기
	}
	return full_time;
}
char* timeConversion(char* s) { // 문제에서 return을 포인터로 받으므로 포인터를 return하는 함수
    char h[2], m[2], se[2]; // 시, 분, 초에 해당하는 배열
    char *str; // return할 문자열
    char *t[] = {"13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"};
    strncpy(h, s, 2); strncpy(m, s+3, 2); strncpy(se, s+6, 2); // 시, 분, 초를 s에서 가져온다
    if (*(s+8)=='P') {
        sprintf(str, "%s:%s:%s", t[atoi(h)-1], m, se); // PM일 때, 24-hour로 변환하여 str에 서식에 맞게 입력
    }
    else sprintf(str, "%s:%s:%s", h, m, se); // AM일 때, str에 서식에 맞게 입력
    return str;
}

감상

visual studio에서는 위의 함수가 실행되지만 사이트에서는 실행이 안 된다. 아직 못 풀었다.
문자열에 약하다는 사실을 새삼 깨달았다. 공부 열심히 해야지.

'문제풀이 > C 문제풀이' 카테고리의 다른 글

[HackerRank]Apple and Orange  (0) 2019.07.03
[HackerRank]Grading Students  (0) 2019.07.01
[HackerRank]Birthday Cake Candles  (0) 2019.06.26
[HackerRank]Mini-Max Sum  (0) 2019.06.25
[HackerRank]Staircase  (0) 2019.05.26