Juni_DEV

[Python, HackerRank] Time-conversion 본문

Coding Interview

[Python, HackerRank] Time-conversion

junni :p 2023. 4. 13. 23:03
반응형
 

Time Conversion | HackerRank

Convert time from an AM/PM format to a 24 hour format.

www.hackerrank.com

주어진 문제

더보기

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example

  • s = '12:01:00PM"
  • Return '12:01:00'.
  • s = '12:01:00AM'
  • Return '00:01:00'.

Function Description

Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.

timeConversion has the following parameter(s):

  • string s: a time in 12 hour format

Returns

  • string: the time in 24 hour format

Input Format

A single string  that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM).

Constraints

  • All input times are valid

Sample Input

07:05:45PM

 Sample Output

19:05:45
 

 

주어진 시간을 AM,PM에서 24시 시간 단위로 변경하기

상황이 3가지로 나뉜다.

  1. 일반적인 PM일때 시간에 +12 하면 되는 경우 (1~12 PM)
  2. AM 12시라 00으로 replace 해야하는 경우 (12 AM)
  3. AM이라 동일해서 수정하지 않아도 되는 경우 (1~11 AM)
def timeConversion(s):
    # Write your code here
    day = s[-2:]
    hour = int(s[:2])
    
    if day == "PM" and hour < 12:
        s = s.replace(s[:2],str(int(s[:2])+12))
    elif day == "AM" and hour == 12 :
        s = s.replace(s[:2],"00")
    
    return s[:-2]

주어진 s는 string 값 -> 슬라이스해서 시간 단위를 replace 하고
뒤에 붙는 AM, PM 을 삭제

 

 

GitHub - SVB-algorithm-study/JuniPark: SVB

SVB. Contribute to SVB-algorithm-study/JuniPark development by creating an account on GitHub.

github.com

 

반응형
Comments