Hackerrank - Time Conversion

Problem Statement
A description of the problem can be found on Hackerrank.

Solution
My solution is folllowing:

After reading an input line I parsed are necessary values.

  • hours part of the input time from 0th to index of first ':'
  • minutes part of the input time from index of first ':' + 1 to index of last ':'
  • seconds part of input time from index of last ':' + 1 to index of last ':' + 3

Then I created new hours part as follows:
Checked if hour is 12

  • then assign to 0
  • otherwise leave it unchanged

And calculated shift hours.
If input time contains 'PM'

  • then assign to 12
  • otherwise assing to 0

In the end created formated string and printed to output.

Note: In most programming languages index in strings are 0-based

I created solution in 4 languages:

All solutions are also available on my GitHub.

Scala

Java

JavaScript

Ruby