Skip to main content

Angle between Hour and Minute Hand

Problem​

Calculate the angle between the hour hand and minute hand.

Note: There can be two angles between hands; we need to print a minimum of two. Also, we need to print the floor of the final result angle. For example, if the final angle is 10.61, we need to print 10.

Examples:​

Example 1:

Input:
H = 9 , M = 0
Output:
90
Explanation:
The minimum angle between hour and minute hand when the time is 9 is 90 degress.

Example 2:

Input:
H = 3 , M = 30
Output:
75
Explanation:
The minimum angle between hour and minute hand when the time is 3:30 is 75 degress.

Your task:​

You don't need to read, input, or print anything. Your task is to complete the function getAngle(), which takes 2 Integers H and M as input and returns the answer.

  • Expected Time Complexity: O(1)O(1)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1≀H≀121 ≀ H ≀ 12
  • 0≀M<600 ≀ M < 60

H and M are Integers

Solution​

Python​

def getAngle(self, H , M):
if H < 0 or M < 0 or H > 12 or M > 60:
print('Wrong input')
return None
if H == 12:
H = 0
if M == 60:
M = 0
H += 1
if H > 12:
H -= 12
hour_angle = 0.5 * (H * 60 + M)
minute_angle = 6 * M
angle = abs(hour_angle - minute_angle)
angle = min(360 - angle, angle)
return int(angle)

Java​

static int getAngle(int H , int M) {
if (H < 0 || M < 0 || H > 12 || M > 60) {
System.out.println("Wrong input");
return -1;
}
if (H == 12) {
H = 0;
}
if (M == 60) {
M = 0;
H += 1;
if (H > 12) {
H -= 12;
}
}
double hourAngle = 0.5 * (H * 60 + M);
double minuteAngle = 6 * M;
double angle = Math.abs(hourAngle - minuteAngle);
angle = Math.min(360 - angle, angle);
return (int) angle;
}

C++​

int getAngle(int H , int M) {
if (H < 0 || M < 0 || H > 12 || M > 60) {
cout << "Wrong input" << endl;
return -1;
}
if (H == 12) {
H = 0;
}
if (M == 60) {
M = 0;
H += 1;
if (H > 12) {
H -= 12;
}
}
double hourAngle = 0.5 * (H * 60 + M);
double minuteAngle = 6 * M;
double angle = abs(hourAngle - minuteAngle);
angle = min(360 - angle, angle);
return static_cast<int>(angle);
}

C​

int getAngle(int H, int M) {
if (H < 0 || M < 0 || H > 12 || M > 60) {
printf("Wrong input\n");
return -1;
}
if (H == 12) {
H = 0;
}
if (M == 60) {
M = 0;
H += 1;
if (H > 12) {
H -= 12;
}
}
double hourAngle = 0.5 * (H * 60 + M);
double minuteAngle = 6 * M;
double angle = fabs(hourAngle - minuteAngle);
angle = fmin(360 - angle, angle);
return (int)angle;
}
  • Time Complexity: O(1)O(1)
  • Auxiliary Space: O(1)O(1)