C/C++ Program to Compute the Angle Between Hands of a Clock

  • 时间:2020-09-11 08:17:29
  • 分类:网络文摘
  • 阅读:110 次

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

Example 1:
Input: hour = 12, minutes = 30
Output: 165

clock-12-30-300x296 C/C++ Program to Compute the Angle Between Hands of a Clock algorithms c / c++ geometry

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

clock-3-30-300x300 C/C++ Program to Compute the Angle Between Hands of a Clock algorithms c / c++ geometry

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

clock-3-15-300x300 C/C++ Program to Compute the Angle Between Hands of a Clock algorithms c / c++ geometry

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.

Hints:
The tricky part is determining how the minute hand affects the position of the hour hand.
Calculate the angles separately then find the difference.

Algorithm to Compute the Angle of the Hour and Minute Hand on the Clock

We can compute the angle between the Hour to the North (clock-wise) in degrees. And the angle between Minute and the North (clock-wise) can be computed in the same way. The answer is minimum of the absolute difference between these two values.

One minute is 6 degrees (there are 60 minutes on the clock). When minute moves, the hour moves proportional. One hour is 30 degrees (there are 12 hours on the clock).

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    double angleClock(int hour, int minutes) {
        double hourAngle = ((hour % 12) + minutes * 1.0/60) * 30;
        double minutesAngle = minutes * 6;
        double a = abs(hourAngle - minutesAngle);
        double b = 360 - a;
        return a < b ? a : b;
    }
};
class Solution {
public:
    double angleClock(int hour, int minutes) {
        double hourAngle = ((hour % 12) + minutes * 1.0/60) * 30;
        double minutesAngle = minutes * 6;
        double a = abs(hourAngle - minutesAngle);
        double b = 360 - a;
        return a < b ? a : b;
    }
};

The Python solution (slightly different) is here: Compute the Angle of the Hour and Minute Hand on a Clock

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
正方体的表面积增加多少  一块横截面是正方形的长方体木料  网站建设老域名是必不可少的一部分  竞价推广怎么做?我来讲讲这4点  这份竞价推广方案 让你不在担心2020年竞价推广没效果  揭秘帮企团队:用源码降低中小企业建站成本  如何分析优化竞价推广效果  竞价推广效果差怎么办?从这8个维度分析着手优化  小说网站建站赚钱怎么操作?  做什么网站赚钱?试试小说网站吧 
评论列表
添加评论