C++: A 24-hour clock class

Design a small class whose data can never hold an impossible time.

What to build

A Clock class that keeps a time of day and moves it forward.

Requirements

  • Keep the time private, so that no outside code can set an impossible value.
  • Give the class a constructor taking hours and minutes, and a member function add(int minutes).
  • Give it a const member function that prints the time as HH:MM.
  • Print the time after every add command.

Input

The first line has the starting hours and minutes. The second line has q. Each of the next q lines is add x.

Output

One line per command: the time as HH:MM.

Constraints

The start is a valid time, 1 ≤ q ≤ 100, and 0 ≤ x ≤ 100000.

Example

Input:

9 5
3
add 10
add 50
add 1440

Output:

09:15
10:05
10:05

Why it works

With one private number and every change going through add, the remainder by 1440 keeps the time valid no matter what is added. Outside code cannot break that rule.

Examples

Example 1 · Input
9 5
3
add 10
add 50
add 1440
Expected output
09:15
10:05
10:05
Example 2 · Input
23 50
2
add 15
add 125
Expected output
00:05
02:10

Hints

Hint 1

Store a single private number, the minutes since midnight, from 0 to 1439.

Hint 2

Adding minutes is `(minutes + x) % 1440`, which wraps past midnight.

Hint 3

Print a leading zero for hours and minutes below 10.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

class Clock {
    int total;   // minutes since midnight, 0 to 1439
public:
    Clock(int h, int m) : total(h * 60 + m) {}
    void add(int minutes) {
        total = (total + minutes) % 1440;
    }
    void print() const {
        int h = total / 60, m = total % 60;
        if (h < 10) cout << "0";
        cout << h << ":";
        if (m < 10) cout << "0";
        cout << m << endl;
    }
};

int main() {
    int h, m, q;
    cin >> h >> m >> q;
    Clock c(h, m);
    while (q-- > 0) {
        string word;
        int x;
        cin >> word >> x;
        c.add(x);
        c.print();
    }
    return 0;
}

Lesson: Classes and objects →