Compute the Angle of the Hour and Minute Hand on a Clock

  • Time:2020-09-13 14:33:25
  • Class:Weblog
  • Read:33

Given a time in the format of hour and minute, calculate the angle of the hour and minute hand on a clock.

clock-3-30 Compute the Angle of the Hour and Minute Hand on a Clock algorithms geometry python

Clock 3:30

This was recently asked by Microsoft. This is not a difficult question. We want to make sure that:

  • The time could be in the format 24-hour. For example, 15:30 is the same as 3:30.
  • The hour minute also moves slightly (portion) when minute hand moves.
  • One minute difference has a 6 rad degree – 60 minutes is 360 degree.

Thus, the following Python code should be straigtforward with O(1) constant in both time and space – just pure math calculations.

1
2
3
4
5
6
7
8
9
10
11
def calcAngle(h, m):
  # hour hand gets percentage angle
  h = (h + (m / 60.0)) * 5 % 60
  diff = abs(h - m)
  return int(diff * 6)
 
if __name__ == "__main__":
  print(calcAngle(3, 30))
  # 75
  print(calcAngle(12, 30))
  # 165
def calcAngle(h, m):
  # hour hand gets percentage angle
  h = (h + (m / 60.0)) * 5 % 60
  diff = abs(h - m)
  return int(diff * 6)

if __name__ == "__main__":
  print(calcAngle(3, 30))
  # 75
  print(calcAngle(12, 30))
  # 165

A slightly different solution in C/C++ can be found here: C/C++ Program to Compute the Angle Between Hands of a Clock

–EOF (The Ultimate Computing & Technology Blog) —

Recommend:
Summits set epoch-making milestone in history of China-Arab ties
In the face of COVID-19 pandemic, China and Arab countries have
15 Macao residents qualify as candidates for deputies to nationa
Study finds genetic solution to pre-harvest sprouting in rice, w
Bodybuilders dying as coaches, judges encourage extreme measures
Malta's Marsaskala, China's Dujiangyan sign sister city agreemen
U.S. mortgage applications continue slide amid surging interest
Russian, UAE presidents discuss bilateral cooperation over phone
Hate crimes in U.S. Los Angeles County rise to highest level sin
Chinese mainland reports 4,031 new local confirmed COVID-19 case
Share:Facebook Twitter
Comment list
Comment add