
I want to know the moment when the second clock hand goes over hour hand or minute hand. So I need exact position of each hand. Fortunately each hand move constant degree every second, Assuming that the rate of hour hand movement is 1, the rate of minute hand movement is 12 and second hand movement is 720. Now I find the over moment by calcurating the difference between pre-clock hand position and post-clock hand for 1 second. if hour or minute hand are in between, call a alert function
class Solution {
public int solution(int h1, int m1, int s1, int h2, int m2, int s2) {
int answer = -1;
Clock clock = new Clock(h1,m1,s1);
int size = (h2-h1) * 3600 + (m2-m1) * 60 + (s2-s1);
for( int i = 0 ; i < size ; i++){
clock.tick();
clock.alert();
}
return clock.alertCount;
}
}
class Clock{
static final int TOTAL_DISTANCE = 43200;
static final int HOUR_HAND_DISTANCE = 1;
static final int MINUTE_HAND_DISTANCE = 12;
static final int SECOND_HAND_DISTANCE = 720;
int hourPoint;
int minPoint;
int secPoint;
int alertCount = 0;
//initialization Clock class
public Clock(int h, int m, int s){
this.hourPoint = h * 3600 + m * 60 + s;
this.minPoint = m * 720 + s * 12;
this.secPoint = s * 720;
alert(); // if clock set up o'clock, count alert
}
// 1 second goes by
public void tick(){
hourTick();
minTick();
secTick();
alertCount += isAlert();
}
//check alert for stopped moment
public void alert(){
if(this.hourPoint == this.secPoint || this.secPoint == this.minPoint){
this.alertCount++;
}
}
//check alert for moving moment
private int isAlert(){
//second hand goes over hour and minute hand
if(this.hourPoint < this.secPoint && this.hourPoint - HOUR_HAND_DISTANCE > this.secPoint - SECOND_HAND_DISTANCE
&& this.minPoint < this.secPoint && this.minPoint - MINUTE_HAND_DISTANCE > this.secPoint - SECOND_HAND_DISTANCE){
return 2;
}
//second hand goes over hour hand
if(this.hourPoint < this.secPoint && this.hourPoint - HOUR_HAND_DISTANCE > this.secPoint - SECOND_HAND_DISTANCE){
return 1;
}
//second hand goes over minute hand
if(this.minPoint < this.secPoint && this.minPoint - MINUTE_HAND_DISTANCE > this.secPoint -SECOND_HAND_DISTANCE){
return 1;
}
return 0;
}
private void hourTick(){
this.hourPoint = (this.hourPoint % TOTAL_DISTANCE) + HOUR_HAND_DISTANCE;
}
private void minTick(){
this.minPoint = (this.minPoint % TOTAL_DISTANCE) + MINUTE_HAND_DISTANCE;
}
private void secTick(){
this.secPoint = (this.secPoint % TOTAL_DISTANCE) + SECOND_HAND_DISTANCE;
}
}