Trusted answers to developer questions

What is the clock angle problem?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The clock angle problem involves finding the angle between the hour and the minute hand of an analog clock at a given time.

The angle is measured in degrees, clockwise from 12:00.

svg viewer

Approach

To solve this problem, consider the rate of change of the angle in degrees per minute. The hour hand of a 12-hour analog clock turns 360° in 12 hours (720 minutes) or 0.5° per minute. The minute hand rotates through 360° in 60 minutes or 6° per minute.

Calculating the angles

Using the information above, the following formula can be used to calculate the angle of the hour hand( with respect to 12:00):

0.5(h60+m)0.5 \cdot (h \cdot 60 + m)

hh and mm are the values of hours and minutes, respectively.

Similarly, the formula to calculate the angle of the minute hand is:

6m6 \cdot m

The difference between the angle of the hour hand and that of the minute hand is the answer to the problem.

Implementation

The clock angle problem is shown in the code below:

#include <iostream>
#include <cmath> // for abs function
using namespace std;
double clockAngle(int hour, int minute)
{
if (hour < 0 || minute < 0)
{
cout << "WRONG INPUT" << endl;
return -1;
}
if (hour == 12)
{
hour = 0;
}
if (minute == 60)
{
minute = 0;
hour += 1;
}
double hourAngle = 0.5 * (hour * 60 + minute);
double minuteAngle = minute * 6;
double clockAngle = abs(hourAngle - minuteAngle);
return min(360 - clockAngle, clockAngle);
}
// driver code
int main()
{
cout << clockAngle(1, 45) << " degrees" << endl;
cout << clockAngle(3, 30) << " degrees" << endl;
cout << clockAngle(9, 15) << " degrees" << endl;
}

One might think the angle for 09:15 should be 180°, but it is slightly less; as the minute hand moves after 09:00, the hour hand also moves forward very slightly, changing the angle to 172.5°.

RELATED TAGS

clock
angle
problem
algorithms
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?