Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format.
Examples:
Input : h1=7, m1=20, h2=9, m2=45 Output : 2 : 25 The current time is 7 : 20 and given time is 9 : 45. The difference between them is 145 minutes. The result is 2 : 25 after converting to h : m format. Input : h1=15, m1=23, h2=18, m2=54 Output : 3 : 31 The current time is 15 : 23 and given time is 18 : 54. The difference between them is 211 minutes. The result is 3 : 31 after converting to h : m format. Input : h1=16, m1=20, h2=16, m2=20 Output : Both times are same The current time is 16 : 20 and given time is also 16 : 20. The difference between them is 0 minutes. As the difference is 0, we are printing “Both are same times”.
Approach:
- Convert both the times into minutes
- Find the difference in minutes
- Ff difference is 0, print “Both are same times”
- Else convert difference into h : m format and print
Below is the implementation.
Python3
def difference(h1, m1, h2, m2):
t1 = h1 * 60 + m1
t2 = h2 * 60 + m2
if (t1 = = t2):
print ( "Both are same times" )
return
else :
diff = t2 - t1
h = ( int (diff / 60 )) % 24
m = diff % 60
print (h, ":" , m)
if __name__ = = "__main__" :
difference( 7 , 20 , 9 , 45 )
difference( 15 , 23 , 18 , 54 )
difference( 16 , 20 , 16 , 20 )
|
Output:
2 : 25
3 : 31
Both are same times
Time complexity: O(1) – the function only performs basic arithmetic operations which take constant time.
Auxiliary space: O(1) – the function uses a constant amount of memory to store the input variables, local variables, and output.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Aug, 2023
Like Article
Save Article