Given two numbers, hour
and minutes
. Return the smaller angle (in degrees) formed between the hour
and the minute
hand.
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
Example 4:
Input: hour = 4, minutes = 50 Output: 155
Example 5:
Input: hour = 12, minutes = 0 Output: 0
Constraints:
1 <= hour <= 12
0 <= minutes <= 59
- Answers within
10^-5
of the actual value will be accepted as correct.
时钟指针的夹角。题意很直观。
思路也很直观,首先定义好一分钟的夹角是6度,一小时的夹角是30度。接着根据这个定义分别算出时针和分针与0:00这个位置的夹角。注意最后两者的夹角一定不会大于360度。
时间O(1)
空间O(1)
Java实现
1 class Solution { 2 public double angleClock(int hour, int minutes) { 3 int oneMinAngle = 6; 4 int oneHourAngle = 30; 5 double minutesAngle = oneMinAngle * minutes; 6 double hoursAngle = (hour % 12 + minutes / 60.0) * oneHourAngle; 7 double diff = Math.abs(hoursAngle - minutesAngle); 8 return Math.min(diff, 360 - diff); 9 } 10 }
JavaScript实现
1 /** 2 * @param {number} hour 3 * @param {number} minutes 4 * @return {number} 5 */ 6 var angleClock = function(hour, minutes) { 7 let oneMinuteAngle = 6; 8 let oneHourAngle = 30; 9 let minutesAngle = oneMinuteAngle * minutes; 10 let hoursAngle = ((hour % 12) + minutes / 60.0) * oneHourAngle; 11 let diff = Math.abs(hoursAngle - minutesAngle); 12 return Math.min(diff, 360 - diff); 13 };