Similar Problems

Similar Problems not available

Angle Between Hands Of A Clock - Leetcode Solution

Companies:

LeetCode:  Angle Between Hands Of A Clock Leetcode Solution

Difficulty: Medium

Topics: math  

The problem "Angle Between Hands of a Clock" on leetcode is a relatively simple problem, where you are given a time in the format of "HH:MM" and are asked to calculate the angle between the hour hand and the minute hand of a clock.

Let us break down the problem into smaller parts and try to solve them.

Step 1: Calculate the angle made by the hour hand

The hour hand moves 360 degrees in 12 hours, or 30 degrees per hour. As there are 60 minutes in an hour, the hour hand moves 0.5 degrees per minute. Therefore, the angle made by the hour hand at a given time can be calculated as follows:

hour_angle = (hour % 12) * 30 + minute * 0.5

Here, we use the modulus operator to keep the hour value within 12, and multiply it by 30 to get the angle made by the hour hand in hours. We then add the extra angle made by the hour hand due to the minutes passed, which is calculated by multiplying the minute value by 0.5.

Step 2: Calculate the angle made by the minute hand

The minute hand moves 360 degrees in 60 minutes, or 6 degrees per minute. Therefore, the angle made by the minute hand at a given time can be calculated as follows:

minute_angle = minute * 6

This is a straightforward calculation as the minute value itself gives us the angle made by the minute hand.

Step 3: Calculate the angle between the hands

To calculate the angle between the hour and minute hands, we need to take the absolute difference between the two angles we calculated in step 1 and step 2. However, we need to be careful to ensure that we take the smallest angle between the two hands.

Therefore, the angle between the hands can be calculated as follows:

angle = abs(hour_angle - minute_angle)

if angle > 180: angle = 360 - angle

Here, we calculate the absolute difference between the two angles and store it in the variable 'angle'. If this value is greater than 180, it means that the angle between the hands is greater than 180 degrees, and we need to take the smaller angle instead. Therefore, we subtract the angle from 360 to get the smaller angle.

Finally, we return the angle as the output of our function.

Here is the complete code that solves the problem:

def angleClock(hour: int, minutes: int) -> float: hour_angle = (hour % 12) * 30 + minutes * 0.5 minute_angle = minutes * 6 angle = abs(hour_angle - minute_angle) if angle > 180: angle = 360 - angle return angle

This is a simple and efficient solution to the "Angle Between Hands of a Clock" problem on leetcode.

Angle Between Hands Of A Clock Solution Code

1