Interview Series: Calculate the angle between hour hand and minute hand


clock has overall 360 degree. So for every minute
minutes degree = 360 / 12 / 60 = 0.5
Is just the number of degrees the hour hand moves per minute. Think about it - the minute hand travels a full 360 each hour. Therefore there are only 60 minutes in a full revolution. 360/60 = 6 degrees per minute for the minute hand.
(hour * 30 + minute * 0.5) - (minute * 6)
def clockangles(hour, minute):
    ans = abs((hour * 30 + minute * 0.5) - (minute * 6))
    return min(360-ans,ans)
Final Solution:
static int calcAngle(double h, double m)
    {
        // validate the input
        if (h <0 || m < 0 || h >12 || m > 60)
            System.out.println("Wrong input");
 
        if (h == 12)
            h = 0;
        if (m == 60) 
            m = 0;
 
        // Calculate the angles moved by hour and minute hands
        // with reference to 12:00
        int hour_angle = (int)(0.5 * (h*60 + m));
        int minute_angle = (int)(6*m);
 
        // Find the difference between two angles
        int angle = Math.abs(hour_angle - minute_angle);
 
        // smaller angle of two possible angles
        angle = Math.min(360-angle, angle);
 
        return angle;
}
Please let me know if you have any doubts and require any clarification on the same.


Comments