using System;
using System.Diagnostics.CodeAnalysis;
public class Clock : IEquatable<Clock>
{
private int _hour;
private int _minute;
public Clock(int hours, int minutes)
{
_hour = (hours // just take the given hours and
+ minutes / 60 // add full hours of minutes if we have more than 60
// minutes
- (minutes < 0 && minutes % 60 != 0 ? 1 : 0) // but the part of negative minutes that is not an full
// hour subtracts one hour, e.g. 01:-10 means (00:50)
) % 24; // at last, ensure hours roll over when longer as a day
if (_hour < 0) _hour += 24; // finally avoid negative hours: e.g. -3 means 21 (3 hours befor midnight)
_minute = minutes % 60; // just take the minutes, but to ensure they roll over when longer as an
// hour, contribution to the hour was already added above
if (_minute < 0) _minute += 60; // e.g. -10 means 50 (10 minutes befor the next full hour)
}
public Clock Add(int minutesToAdd) => new Clock(_hour, _minute + minutesToAdd);
public Clock Subtract(int minutesToSubtract) => new Clock(_hour, _minute - minutesToSubtract);
public override string ToString() => $"{_hour:00}:{_minute:00}";
public bool Equals([AllowNull] Clock other)
{
if (other == null)
return false;
if (this == other)
return true;
return _hour == other._hour && _minute == other._minute;
}
// these methods are not needed to make the tests running but it is recommended to override Equals(object) and
// GetHashCode() when implementing IEquatable
public override bool Equals(object obj) => Equals(obj as Clock);
public override int GetHashCode() => _hour * 60 + _minute;
}
Comments