Angles & Degrees-Q1
Problem: Given a time, calculate the angle between the hour and minute hands.
eg. 12:30AM => 180 degrees, 3:30PM => 0 degrees, 6:35 => 30 degrees
For example if the hour hand is at 12 and minute hand is at 30 then the angle between them is 180. My solution to this problem was to take 360 degrees and divide it by 12 to get the degrees per hour. Then take 360 degrees and divide it by 60 to get degrees per min. Every min represents 6 degrees and each hour represents 30 degrees.
1
2
3
4
5
6
7
8
public static int getAngle(int hour, int min ) {
//calculate delta degree per hour
int stepHours = DEGREES_IN_CIRCLE/HOURS_ON_CLOCK;
//calculate delta degree per min
int stepMins = DEGREES_IN_CIRCLE/MINS_ON_CLOCK;
return Math.abs(stepHours*hour - stepMins*min);
}
The only thing with this approach is that the angle of the minutes could be larger then the hours so you have to absolute value the number at the end.
Sources
- Cracking the code interview 5th edition