[LeetCode] 1344. Angle Between Hands of a Clock 時鐘指針的夾角
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
這道題說給定了任意一個時間,讓求時針分針之間的最小夾角。想必我們都對鐘表都不陌生,一圈 360 度,一共 12 個數(shù)字,每兩個數(shù)字之間為 30 度,有的表會在每兩個數(shù)字之間分為五段,則每一段為6度。整點的夾角比較容易求,因為分針都指向 12,時針都精確地指向某個數(shù)字,比如六點整的時候時針分針夾角為 180 度。但對于任意時間,比如1點30分的時候,時針就指向數(shù)字1和2的正中間,時針的具體位置其實是根據(jù)分針指向的位置來確定的,分針走過的 360 度中的百分比,就等于時針走過的 30 度中的百分比。
這里以 12 點的位置為0度,則可以根據(jù)小時數(shù)先求出整點時的角度,這里由于 12 點就是0度,所以用個小 trick,hour 對 12 取余,然后再乘以 30,就是該小時數(shù)整點時的時針角度。然后再計算偏移量,根據(jù)分鐘數(shù)除以60,再乘以 30 度,就是時針的偏移度數(shù)了。然后分針的角度就比較好算了,每一分鐘的角度是6度,所以分鐘數(shù)直接乘以6就行了。接下來算夾角,直接二者相減,并取絕對值,由于要返回最小的夾角,則跟其補角比較一下,返回較小值即可,參見代碼如下:
class Solution {
public:
double angleClock(int hour, int minutes) {
double hourDegree = (hour % 12) * 30 + double(minutes) / 60 * 30;
double minDegree = minutes * 6;
double diff = abs(hourDegree - minDegree);
return min(diff, 360 - diff);
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1344
參考資料:
https://leetcode.com/problems/angle-between-hands-of-a-clock


浙公網(wǎng)安備 33010602011771號