Microsoft Interview Question
Software Engineer / DevelopersTeam: Windows Live
Country: United States
Interview Type: In-Person
That angle is a periodic function. Inside its period the function is linear. Thus all we need is find a period. If x is a period and minute hand rotates 12 time faster than the hour hand, then we can write down equation for that:12x-12=x. Thus x=12/11of hour is a period when the minute hand over the hour hand. It's very efficient to store pre calculations in constants. So the function requires only two operations to be computed. One should note that function returns angle in radians.
public class Clock
{
private static long Period = TimeSpan.FromHours(1).Ticks * 12 / 11;
private static double Scale = 2 * Math.PI / Period;
public double GetAngle(TimeSpan time)
{
return Scale * (time.Ticks % Period);
}
}
float getAngle(int hour, int min)
{
float hourAngle = (hr%12)*30 + 1/2*(min%60);
float minAngle = (min%60)*6;
return (abs(hourAngle-minAngle));
}
I saw this question a long time ago.
Most people forget to take into account that not only does the number of minutes affect the position of the hour hand, but so does the current number of seconds! Here's a solution:
this assumes the following Time struct.
struct Time
{
int hour;
int min;
int sec;
};
double Problems::Problem1::findAngle(Time t)
{
//Ensure correct values.
//Should also check negatives, but we can skip these for now.
while (t.sec >= 60)
{
t.sec = t.sec - 60;
t.min++;
}
while (t.min >= 60)
{
t.min = t.min - 60;
t.hour++;
}
t.hour = t.hour % 12;
//first find angle from 0 (straight up) of both.
double angleHour = (t.hour / 12.0) + (t.min / (12.0 * 60.0)) + (t.sec / (12.0 * 60.0 * 60.0));
double angleMin = (t.min / 60.0) + (t.sec / (60.0 * 60.0));
//results are 0-1(.99999...) value of how far along the clock each hand is.
//for instance: .5 represents straight down.
if (angleHour > angleMin)
{
//hour hand is further, so we need to swap. (This avoids and problems with negatives, and no need for absolute value)
double t = angleHour;
angleHour = angleMin;
angleMin = t;
}
//see if there is more than a .5 difference, if so, we need the other angle (smallest angle of the two)
double difference = angleMin - angleHour;
if (difference > .5)
{
difference = 1 - difference;
}
//Assuming we want the result in Degrees
return difference * 360;
}
The hour hand move 360 deg in 12 Hr i.e every 12 * 60 = 720 min it rounds 360 deg.
- jainrajrahul January 17, 2012so per min 0.5 deg.
And minute hand move 360 deg in 60 min i.e 6 deg per min.
Angle of Hr Hand = 0.5 * (60H + M)
Angle of Min = 6 * M
Theta angle = Angle of Hr hand - Angle of Min