2 minutes
Leetcode July: Clock Hands Angle
Today I’m looking at a neat little Leetcode July Challenge problem, Angle Between Hands on a Clock. It’s a pretty straightforward problem, a little practical, a little mathematical. We’re given two integer values representing the hour and minute on a 12-hour analog clock face and asked to return the least angle between the hour and minute hand with a precision of $10^{-5}$. So, we’ll find the absolute angle of each hand relative to 12:00, and then find their difference. This problem wouldn’t be too bad without any additional information, but a visual of a couple example clockfaces is useful for hitting on the little twist to this problem.
hour = 12, minute = 30
minimum angle = 165
We can see from that example that the trick is in adding additional degrees to the hour hand based on the value of the minute hand. Other than that, we just need to do a quick calculation to determine how many degrees each minute and hour represent on the clockface, which as a four quadrant shape has $360^o$. There are 60 minutes on the clockface, so each minute represents 360/60, or $6^o$. Similarly, there 12 hours so 360/12, or $30^o$ per hour. To add the minute modifier to the hour hand we take divide the degrees of a single hour by possible minutes on the clockface and get 30/60, or $0.5^o$ per minute. Let’s just put those together and put in a couple checks to make sure we’re getting the minimum positive angle, and we’re done!
double angleClock(int hour, int minutes) {
float minuteAngle = minutes*6;
float hourAngle = hour * 30 + minutes * 0.5;
// make sure we're taking the positive angle,
double angle = abs(minuteAngle - hourAngle);
// and the minimum angle.
return min(angle, 360-angle);
}
That was pretty fun! Check back tomorrow for more!