The hour and minute hands move at different rates. By calculating their positions in degrees, we can find the absolute difference and ensure we return the smaller angle (≤180°). For example, at 3:15, the hour hand is at 97.5° and the minute hand at 90°, so the angle is 7.5°.
classSolution {
publicdoubleangleClock(int hour, int minutes) {
double ha = (hour % 12) * 30 + minutes * 0.5;
double ma = minutes * 6;
double ans = Math.abs(ha - ma);
return ans > 180 ? 360 - ans : ans;
}
}
1
2
3
4
5
6
7
8
classSolution {
funangleClock(hour: Int, minutes: Int): Double {
val ha = (hour % 12) * 30 + minutes * 0.5val ma = minutes * 6.0val ans = kotlin.math.abs(ha - ma)
returnif (ans > 180) 360 - ans else ans
}
}
1
2
3
4
5
6
classSolution:
defangleClock(self, hour: int, minutes: int) -> float:
ha: float = (hour %12) *30+ minutes *0.5 ma: float = minutes *6 ans: float = abs(ha - ma)
return360- ans if ans >180else ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnangle_clock(hour: i32, minutes: i32) -> f64 {
let ha = (hour %12) asf64*30.0+ minutes asf64*0.5;
let ma = minutes asf64*6.0;
letmut ans = (ha - ma).abs();
if ans >180.0 {
ans =360.0- ans;
}
ans
}
}
This variant takes time as a string and rounds the result to the nearest degree. The core calculation remains the same, but we need to parse the input and round the output. For the bonus question, we need to find when both hands overlap.
classSolution {
public:int angleClockFromString(string time) {
int colon = time.find(':');
int hour = stoi(time.substr(0, colon));
int minutes = stoi(time.substr(colon +1));
double ha = (hour %12) *30+ minutes *0.5;
double ma = minutes *6;
double ans = abs(ha - ma);
if (ans >180) ans =360- ans;
returnround(ans);
}
vector<string> getZeroAngleTimes() {
vector<string> times;
// Hands overlap 11 times in 12 hours
for (int i =0; i <11; i++) {
double minutes = i *720.0/11; // 720 minutes in 12 hours / 11 overlaps
int h = (int)(minutes /60) %12;
int m = (int)(minutes) %60;
int s = (int)((minutes - (int)minutes) *60);
char buffer[10];
sprintf(buffer, "%02d:%02d:%02d", h ==0?12: h, m, s);
times.push_back(string(buffer));
}
return times;
}
};