Skip to content

Instantly share code, notes, and snippets.

@petercr
Created February 9, 2022 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petercr/b99aa83a8c59d47fb32a7dd84fb7621f to your computer and use it in GitHub Desktop.
Save petercr/b99aa83a8c59d47fb32a7dd84fb7621f to your computer and use it in GitHub Desktop.
The code I used to solve the Time Conversion algorithm on HackerRank
function timeConversion(s) {
// Take the time passed in and check for AM | PM
// If the time is AM, then just remove the AM unless it's 12
if (s.endsWith("AM")) {
// add the first 2 numbers from s to firstNumSet
let firstNumSet = parseInt(s.substring(0,2));
// if first number is 12, make it 00
if (firstNumSet === 12) {
firstNumSet = "00";
}
// if number is less than 10 add a zero in front
else if (firstNumSet < 10) {
firstNumSet = 0 + firstNumSet.toString();
}
// take the time and just remove AM from end
let answer = s.replace("AM", "");
// remove the first set of numbers
answer = answer.substring(2,8);
// add back on the first number
answer = firstNumSet + answer;
return answer;
}
else {
// add the first 2 numbers from s to firstNumSet
let firstNumSet = parseInt(s.substring(0,2));
// unless first number is 12, add 12 to it
if (firstNumSet !== 12) {
firstNumSet += 12;
}
// remove the PM from end
let answer = s.replace("PM", "");
// remove the first set of numbers
answer = answer.substring(2,8);
// then add time back to front of String
answer = firstNumSet + answer;
// and return the final value
return answer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment