[LeetCode] Minimum Number of Operations to Convert Time

2224. Minimum Number of Operations to Convert Time

You are given two strings current and correct representing two 24-hour times.

24-hour times are formatted as “HH:MM”, where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.

In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.

Return the minimum number of operations needed to convert current to correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
pair<int,int> parse(string& s) {
int h = (s[0] - '0') * 10 + (s[1] - '0');
int m = (s[3] - '0') * 10 + (s[4] - '0');
return {h, m};
}
int operation(int& diff, int time) {
if(diff >= time) {
int d = diff / time;
diff -= time * d;
return d;
}
return 0;
}
public:
int convertTime(string current, string correct) {
if(current == correct)
return 0;
auto [ct, cm] = parse(current);
auto [gt, gm] = parse(correct);
int diff = (gt - ct) * 60 + gm - cm;
int op = 0;
op += operation(diff, 60);
op += operation(diff, 15);
op += operation(diff, 5);
op += operation(diff, 1);
return op;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/03/PS/LeetCode/minimum-number-of-operations-to-convert-time/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.