Created
March 16, 2016 04:22
-
-
Save chrisciampoli/ff893f53add3ff7d6ff5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Clock Angle Problem | |
BY SJ · FEBRUARY 20, 2015 | |
Objective: Find the Angle between hour hand and minute hand at the given time. | |
Example: | |
Time : 12:45 | |
Input : hour = 12, Minute = 45 | |
Output : 112.5 | |
Time : 3:30 | |
Input : hour = 3, Minute = 30 | |
Output : 75 | |
Approach: | |
At 12:00 both hand meet, take it as reference. | |
Angle between hand and minute = angle of hour hand ~ angle of minute hand. | |
return minimum(angle, 360-angle) | |
hour hand moves 360 in 12 hours => 360/12 = 30 degree in one hour or 0.5 degree in 1 min | |
Minute hand moves 360 in 60 mins => 360/60 = 6 degree in one min | |
So if given time is h hours and m mins, hour hand will move (h*60+m)*0.5 and minute hand will move 6*m | |
Code: | |
public class AngleHourMinute { | |
public static double angle(int hour, int minute) { | |
if (hour < 0 || minute < 0) { | |
return -1; | |
} | |
if (hour == 12) { | |
hour = 0; | |
} | |
if (minute == 60) { | |
minute = 0; | |
hour += 1; | |
} | |
double hourAngle = (hour * 60 + minute) * 0.5; | |
double minAngle = minute * 6; | |
double bwAngle = Math.abs(hourAngle - minAngle); | |
return Math.min(360 - bwAngle, bwAngle); | |
} | |
public static void main(String[] args) { | |
System.out.println(angle(12, 45)); | |
System.out.println(angle(3, 30)); | |
System.out.println(angle(2, 23)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment