Saturday, August 5, 2017

Time Conversion - Problem from HackerRank

Problem Statement:

Given a time in -hour AM/PM format, convert it to military (-hour) time.
Note: Midnight is  on a -hour clock, and  on a -hour clock. Noon is  on a -hour clock, and  on a -hour clock.
Input Format
A single string containing a time in -hour clock format (i.e.:  or ), where  and .
Output Format
Convert and print the given time in -hour format, where .

Problem Solution using python 2.7.6:

s = raw_input().strip()
def timeconversion(s):
    hh = s.split(':')[0]
    mm = s.split(':')[1]
    ss = s.split(':')[2][:2]
   
    if 'PM' in s.split(':')[2]:
        if int(hh) == 12:
            return hh+':'+mm+':'+ss
        else:           
            hh = 12 + int(hh)           
            if hh >= 24:
                hh = '00'
                return hh+':'+mm+':'+ss
            else:
                return str(hh)+':'+mm+':'+ss
    if 'AM' in s.split(':')[2]:
        if int(hh) == 12:
            return '00'+':'+mm+':'+ss
        else:
            return hh+':'+mm+':'+ss
print timeconversion(s)


No comments:

Post a Comment