The LeetCode problem "Angle Between Hands of a Clock" asks you to calculate the smallest angle in degrees between the hour and minute hands of an analog clock, given a specific time.
You are given two integers:
hour
: an integer between 1 and 12 (inclusive) representing the hour handminutes
: an integer between 0 and 59 (inclusive) representing the minute handConstraints:
hour
≤ 12minutes
≤ 59To solve this problem, let's first visualize how the hands of a clock move:
The challenge is to correctly calculate both hand positions and then find the smallest angle between them.
hour_angle = (hour % 12) * 30 + (minutes * 0.5)
minute_angle = minutes * 6
angle = abs(hour_angle - minute_angle)
return min(angle, 360 - angle)
This approach is efficient and direct, using only a few arithmetic operations.
Let's consider the input hour = 3
, minutes = 15
.
hour_angle = (3 % 12) * 30 + (15 * 0.5) = 90 + 7.5 = 97.5°
minute_angle = 15 * 6 = 90°
angle = abs(97.5 - 90) = 7.5°
For hour = 12
, minutes = 30
:
(12 % 12) * 30 + (30 * 0.5) = 0 + 15 = 15°
30 * 6 = 180°
abs(15 - 180) = 165°
To solve the "Angle Between Hands of a Clock" problem, we use the fact that the hour hand and minute hand move at constant, predictable rates. By calculating the position of each hand in degrees, finding the absolute difference, and returning the smaller angle (if necessary by subtracting from 360°), we arrive at a clean, efficient, and accurate solution. The key insight is to model the positions mathematically rather than simulating the clock's movement.
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour_angle = (hour % 12) * 30 + (minutes * 0.5)
minute_angle = minutes * 6
angle = abs(hour_angle - minute_angle)
return min(angle, 360 - angle)
class Solution {
public:
double angleClock(int hour, int minutes) {
double hour_angle = (hour % 12) * 30 + (minutes * 0.5);
double minute_angle = minutes * 6;
double angle = fabs(hour_angle - minute_angle);
return std::min(angle, 360 - angle);
}
};
class Solution {
public double angleClock(int hour, int minutes) {
double hourAngle = (hour % 12) * 30 + (minutes * 0.5);
double minuteAngle = minutes * 6;
double angle = Math.abs(hourAngle - minuteAngle);
return Math.min(angle, 360 - angle);
}
}
var angleClock = function(hour, minutes) {
let hourAngle = (hour % 12) * 30 + (minutes * 0.5);
let minuteAngle = minutes * 6;
let angle = Math.abs(hourAngle - minuteAngle);
return Math.min(angle, 360 - angle);
};