Description
Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.
Answers within 10-5 of the actual value will be accepted as correct.
Example 1:
Input: hour = 12, minutes = 30 Output: 165
Example 2:
Input: hour = 3, minutes = 30 Output: 75
Example 3:
Input: hour = 3, minutes = 15 Output: 7.5
Constraints:
1 <= hour <= 120 <= minutes <= 59
Solutions
This JavaScript function calculates the smallest angle between the hour and minute hands on a traditional clock. First, it determines the minute hand's position in degrees by multiplying the minutes by 6 (since a full circle is 360 degrees and has 60 minutes). Next, it calculates the hour hand's position by multiplying the hour by 30 degrees, adding a tiny adjustment (0.5 degrees per minute) because the hour hand drifts slightly as minutes pass. After finding the absolute difference between these two positions, the function compares this angle to its opposite side (360 minus the difference) and returns the smaller value, ensuring the final output is always the shortest path between the two hands (180 degrees or less).
/**
* @param {number} hour
* @param {number} minutes
* @return {number}
*/
var angleClock = function(hour, minutes) {
const betweenMinutes = minutes * 6;
const betweenHour = hour * 30 + (minutes / 2);
const diff = Math.abs(betweenMinutes - betweenHour);
return Math.min(diff, 360 - diff);
};