[Hackerrank] Time Conversion

Problem

Given a time in AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.
Input Format
A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01hh12.
Output Format
Convert and print the given time in 24-hour format, where 00hh23.
Sample Input
07:05:45PM
Sample Output
19:05:45
Explanation
7 PM is after noon, so you need to add 12 hours to it during conversion. 12 + 7 = 19. Minutes and seconds do not change in 12-24 hour time conversions, so the answer is 19:05:45.

Analysis

  • 首先截取后两位字母,判断是AM还是PM
  • 注意关于时间,只需要改hour
    • 取hour
    • 如果PM
      • 若hour<12, 则加12,否则不变
      • 如 12:xx:xxPM, should be 12:xx:xx
      • 11:xx:xxPM should be 23:xx:xx
    • 如果AM
      • 若hour>12, 则转为0
      • 否则不变

Code

Leave a Reply

Your email address will not be published. Required fields are marked *

*