Given two numbers, hour
and minutes
, return the smaller angle (in degrees) formed between the hour
and the minute
hand.
Answers within 10-5
of the actual value will be accepted as correct.
Example 1:
Input: hour = 12, minutes = 30 Output: 165
Example 2:
Input: hour = 3, minutes = 30 Output: 75
Example 3:
Input: hour = 3, minutes = 15 Output: 7.5
Constraints:
1 <= hour <= 12
0 <= minutes <= 59
This problem involves calculating the smaller angle between the hour and minute hands of a clock given the hour and minute.
Understanding the Problem:
A clock has 360 degrees. The minute hand moves 360 degrees in 60 minutes (6 degrees per minute). The hour hand moves 360 degrees in 12 hours (30 degrees per hour) or 0.5 degrees per minute.
Approach:
Calculate the position of the minute hand: The minute hand's position is simply minutes * 6
.
Calculate the position of the hour hand: The hour hand's position is more complex. It moves 30 degrees per hour, plus an additional 0.5 degrees for each minute past the hour. Therefore, the hour hand's position is (hour % 12) * 30 + minutes * 0.5
. We use the modulo operator (% 12
) to handle the case where the hour is 12 (which is equivalent to 0).
Calculate the difference: Find the absolute difference between the hour hand's and minute hand's positions.
Find the smaller angle: The smaller angle is the minimum of the difference and 360 - difference
. This accounts for cases where the difference is greater than 180 degrees.
Time and Space Complexity:
Code Implementation (Python):
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
h = (hour % 12) * 30 + minutes * 0.5 # Hour hand position
m = minutes * 6 # Minute hand position
diff = abs(h - m) # Absolute difference
return min(diff, 360 - diff) # Smaller angle
Code Implementation in other languages:
The approach remains the same across different programming languages. The core calculations are identical, only the syntax varies slightly. See the provided solutions in Java, C++, Go and Typescript for examples. These solutions all reflect the same algorithmic approach with minor adjustments for language-specific features (e.g., Math.abs()
vs. abs()
).
Example Walkthrough (Hour = 3, Minutes = 30):
30 * 6 = 180
degrees.(3 % 12) * 30 + 30 * 0.5 = 90 + 15 = 105
degrees.abs(180 - 105) = 75
degrees.min(75, 360 - 75) = 75
degrees.The code efficiently computes this smaller angle directly, providing a clear and concise solution to the problem.