Angle Between Hands of a Clock
Problem
Given two numbers hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hands of a clock.
hour = 12, minutes = 30165def angle_clock(hour, minutes):
h = (hour % 12) * 30 + minutes * 0.5
m = minutes * 6
diff = abs(h - m)
return min(diff, 360 - diff)
function angleClock(hour, minutes) {
const h = (hour % 12) * 30 + minutes * 0.5;
const m = minutes * 6;
const diff = Math.abs(h - m);
return Math.min(diff, 360 - diff);
}
class Solution {
public double angleClock(int hour, int minutes) {
double h = (hour % 12) * 30.0 + minutes * 0.5;
double m = minutes * 6.0;
double diff = Math.abs(h - m);
return Math.min(diff, 360 - diff);
}
}
double angleClock(int hour, int minutes) {
double h = (hour % 12) * 30.0 + minutes * 0.5;
double m = minutes * 6.0;
double diff = fabs(h - m);
return min(diff, 360.0 - diff);
}
Explanation
The idea is to figure out the position of each hand in degrees measured from 12 o'clock, take the difference, and then keep the smaller of the two angles the hands form.
A full circle is 360°. The minute hand sweeps that in 60 minutes, so each minute is 6 degrees: m = minutes * 6. The hour hand moves 30° per hour (360/12), but it also creeps forward as minutes pass, gaining 0.5 degree per minute. So h = (hour % 12) * 30 + minutes * 0.5. The % 12 turns 12 o'clock into 0.
The raw gap is diff = abs(h - m). But two hands always make two angles that add up to 360°, and we want the smaller one, so we return min(diff, 360 - diff).
Example: hour = 12, minutes = 30. Minute hand sits at 30 * 6 = 180°. Hour hand at 0 + 30 * 0.5 = 15°. The difference is |180 - 15| = 165°, and since 360 - 165 = 195 is larger, the answer is 165°.