Hi, here’s your problem today. This problem was recently asked by Microsoft:
Given a time in the format of hour and minute, calculate the angle of the hour and minute hand on a clock.
def calcAngle(h, m): # Fill this in. print calcAngle(3, 30) # 75 print calcAngle(12, 30) # 165
solution:
Java:
package testAlgorithms; public class ClockAngleProblem { public static void main(String[] args) { System.out.println(calcAngle(3, 30)); System.out.println(calcAngle(12, 30)); System.out.println(calcAngle(12, 45)); System.out.println(calcAngle(12, 0)); System.out.println(calcAngle(3, 30)); System.out.println(calcAngle(2, 23)); System.out.println(calcAngle(2, 60)); } /** * 必须是浮点型,因为没法保证角度一定是int * the returned value must be float or double type * @param hour * @param minute * @return */ static double calcAngle(int hour, int minute) { if (hour >= 12) { hour = hour - 12; } // an hour is equal to 30 degree double hMultiplier = 360 / 12; // a minute is equal to 6 degree double mMultiplier = 360 / 60; double angle = Math.abs(hMultiplier * (hour + (minute / 60.0)) - mMultiplier * minute); //需要的是小于等于180 //we need the angle that is less than or equal to 180 degree return Math.min(angle, 360 - angle); } } /* output: 75.0 165.0 112.5 0.0 75.0 66.5 90.0 */