Created
June 11, 2019 01:07
-
-
Save kei9327/768162233f22db725afe3c876a232801 to your computer and use it in GitHub Desktop.
HackerRank>Algorithm>Warmup>timeConversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
string *subTimeString(string s, string str_arr[], int &str_cnt) { | |
str_cnt = 0; | |
char *str_buff = new char[s.length()]; | |
strcpy(str_buff, s.c_str()); | |
char *tok = strtok(str_buff, ":"); | |
while (tok != nullptr) { | |
str_arr[str_cnt++] = string(tok); | |
tok = strtok(nullptr, ":"); | |
} | |
return str_arr; | |
} | |
/* | |
* Complete the timeConversion function below. | |
*/ | |
string timeConversion(string s) { | |
string str_arr[s.length()]; | |
int str_cnt; | |
string sub1 = s.substr(0, s.length() - 2); | |
string sub2 = s.substr(s.length() - 2, s.length() - 1); | |
subTimeString(sub1, str_arr, str_cnt); | |
string result = ""; | |
if (sub2.compare("PM") == 0) { | |
std::string::size_type sz; // alias of size_t | |
int i_dec = std::stoi(str_arr[0], &sz); | |
if(i_dec != 12){ | |
i_dec += 12; | |
} | |
result.append(std::to_string(i_dec)); | |
result.append(":"); | |
result.append(str_arr[1]); | |
result.append(":"); | |
result.append(str_arr[2]); | |
} else { | |
std::string::size_type sz; // alias of size_t | |
if (int i_dec = std::stoi(str_arr[0], &sz) == 12) { | |
result.append("00"); | |
} else { | |
result.append(str_arr[0]); | |
} | |
result.append(":"); | |
result.append(str_arr[1]); | |
result.append(":"); | |
result.append(str_arr[2]); | |
} | |
return result; | |
} | |
int main() | |
{ | |
ofstream fout(getenv("OUTPUT_PATH")); | |
string s; | |
getline(cin, s); | |
string result = timeConversion(s); | |
fout << result << "\n"; | |
fout.close(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment