Solving Code Wars 5kyu — Human Readable Time

Rebecca Robbins
2 min readAug 9, 2021

--

Today we’re going to solve a 5kyu problem from Codewars, Human Readable Code. The problem states…

Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)

HH = hours, padded to 2 digits, range: 00 - 99

MM = minutes, padded to 2 digits, range: 00 - 59

SS = seconds, padded to 2 digits, range: 00 - 59

The maximum time never exceeds 359999 (99:59:59)

Easy peasy, yeah? Yeah. We need to convert seconds into hours first, then minutes, then we’ll just have seconds left. After we determine our hours, minutes, and seconds we can just return those, so let’s get to it.

First, let’s take care of our extremes. Our argument will be an integer between 0and 359999. If it’s less than 0 or more than 359999 we’ll return null and then if it’s 0 we have no need to do any math and we can just return zeros.

Great. Now let’s figure out what time it is.

First, let’s find out how many hours there are. We can just divide the seconds we were given by 3600 because that’s how many seconds are in an hour. We’ll use Math.floor so that we get a whole number, then we’ll have to subtract the number of seconds we’ve now accounted for in hours from our original seconds argument.

We’ve been told that we’re to return the time in HH:MM:SS format, so we need to take into account if the hours returned are a single digit by reassigning our hours variable with a leading zero.

So now let’s do the exact same thing with minutes.

Now, all we have left should be seconds, less than 60 to be exact, so no more math, but we do need to take into account whether or not we have less than 10 seconds, so we can include that leading zero.

Now that we have three variables, hours, minutes, and seconds, all that’s left is to return the time in the format asked above, and we can do that using string interpolation.

And there you have it! A rather straightforward solution to a 5kyu Codewars problem!

Thanks for reading! Stay tuned for more algorithm solutions both here and on my youtube!

--

--