Created
February 9, 2022 02:10
-
-
Save petercr/b99aa83a8c59d47fb32a7dd84fb7621f to your computer and use it in GitHub Desktop.
The code I used to solve the Time Conversion algorithm on HackerRank
This file contains hidden or 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
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