I was given this interview question recently:
Given a 12-hour analog clock, compute in degree the smaller angle between the hour and minute hands. Be as precise as you can.
I'm wondering what's the simplest, most readable, most precise algorithm is. Solution in any language is welcome (but do explain it a bit if you think it's necessary).
Summary: The angle between the hour hand and minute hand at 4'o clock in an analog clock is 120 degrees.
Angle from hour hand to minute hand at 10:54 54 times 6 degrees is 324 degrees.
Hence, the angle between the hour and minute hands of a clock when it strikes 2:10 pm will be 5 degrees.
It turns out that Wikipedia does have the best answer:
// h = 1..12, m = 0..59 static double angle(int h, int m) { double hAngle = 0.5D * (h * 60 + m); double mAngle = 6 * m; double angle = Math.abs(hAngle - mAngle); angle = Math.min(angle, 360 - angle); return angle; }
Basically:
0.5
degrees per minute6
degrees per minuteProblem solved.
And precision isn't a concern because the fractional part is either .0
or .5
, and in the range of 0..360
, all of these values are exactly representable in double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With