LeetCode 1344. Angle Between Hands of a Clock

Question

Given two numbers, hour and minutes. Return the smaller angle (in sexagesimal units) formed between the hour and the minute hand.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input: hour = 12, minutes = 30
Output: 165

Input: hour = 3, minutes = 30
Output: 75

Input: hour = 3, minutes = 15
Output: 7.5

Input: hour = 4, minutes = 50
Output: 155

Input: hour = 12, minutes = 0
Output: 0

Solution

it’s Math problem. We have to calcuate the angle of each hour and each minute. And we need to calculate the hour angle which also needs to add the influence from minute, and then caculate the minute angle. At the end, we let the bigger one minus smaller one and also consider the 360 minus this.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
//time:O(1) space:O(1)
public double angleClock(int hour, int minutes) {
double dh = hour;
double dm = minutes;

double hangle = dh * 360 / 12 + dm / 60 * (360 / 12);

hangle %= 360;

double mangle = dm / 60 * 360;
if (mangle > hangle) return Math.min(mangle - hangle, 360 - (mangle - hangle));
return Math.min(hangle - mangle, 360 - (hangle - mangle));
}