-
[HackerRank] Time Conversion c++Coding Test/HackerRank 2022. 7. 18. 13:30728x90
- Problem
Given a time in 12 -hour AM/PM format, convert it to military (24-hour) time.
Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.- Example
- s = '12:01:00PM'
Return '12:01:00'.
- s = '12:01:00AM'
Return '00:01:00'.
- Constraints
All input times are valid
- Sample Input
07:05:45PM
- Sample Output
19:05:45
- Solutions
문자열을 parsing 하여 문제를 접근하려고 했는데
파싱하지 않고 isdigit() 함수를 사용하여 숫자 검사하는 방법으로 문제를 풀었다.
파싱해서 검사하는것보다 숫자를 검사하는게 더 간단하게 문제를 풀 수 있었다.
string timeConversion(string s) { int time = 0; char ch; vector<int> vec; for(auto it : s){ if(isdigit(it)){ time = time * 10 + (it - 48); } else{ vec.push_back(time); time = 0; if(it == 'A' || it == 'P'){ ch = it; break; } } } if(ch == 'P' && vec[0] < 12){ vec[0] = vec[0] + 12; } else if(ch == 'A' && vec[0] == 12){ vec[0] = 0; } string res(""); for(auto &it : vec){ string tmp(""); if(it < 10){ tmp = "0"+to_string(it); } else{ tmp = to_string(it); } res += tmp + ":"; } res = res.erase(res.size()-1); return res; }
728x90'Coding Test > HackerRank' 카테고리의 다른 글
[HackerRank] Grading Students c++ (0) 2022.07.18 [HackerRank] Compare the Triplets c++ (0) 2022.07.18 [HackerRank] Birthday Cake Candles c++ (0) 2022.07.18 [HackerRank] Mini-Max Sum c++ (0) 2022.07.16 [HackerRank] Staircase c++ (0) 2022.07.16