我不知道我是在失去理智还是甚至可能。
顺便说一句,我没有使用任何标准库,因此这不依赖于语言,因此它就在这里,而不是在stackoverflow上。
我有两个时间段以int格式传递给我。
1st period-
Start Time:
End Time:
2nd period-
Start Time:
End Time:
Int的是午夜以来的分钟,所以早上7点是420分钟。
所以我想写的函数的一个例子是:
bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime,
int secondStartTime, int secondEndTime)
{
....
}
我甚至不确定这可以做到。
P.S。跨越午夜是好的,但它没有必要。 期间不能重叠。
So it could look like this:
420, 1140, 1260, 419
7am, 7pm, 9pm, 6:59am
- Valid
This would be valid since it doesn't span over 24 hours.
420, 1140, 1260, 421
7am, 7pm, 9pm, 7:01am
- Not valid
420, 60, 120, 419
7am, 1am,2am, 6:59am
- Valid
我必须确保从第1期开始时间到第2期结束时间不超过24小时。
答案 0 :(得分:6)
如果一个时期可以在周一开始并在周三结束,那么这个问题就无法解决;否则,这里有一些C#给你:
int MinutesBetweenTwoTimes(int time1, int time2)
{
return time1 < time2 ? time2 - time1 : (1440-time1) + time2;
}
bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime,
int secondStartTime, int secondEndTime)
{
int totalSpannedTime = MinutesBetweenTwoTimes(firstStartTime, firstEndTime)
+ MinutesBetweenTwoTimes(firstEndTime, secondStartTime)
+ MinutesBetweenTwoTimes(secondStartTime, secondEndTime);
return totalSpannedTime > 1440;
}
答案 1 :(得分:0)
我可能会误解,但你不能只检查是否 firstStartTime&lt; = secondEndTime?
答案 2 :(得分:0)
如果我读得对,我认为这有效,不是吗?
bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime,
int secondStartTime, int secondEndTime)
{
// Logically, you'll only have a span > 24 hours if one of them spans midnight
if ( firstStartTime > firstEndTime || secondStartTime > secondEndTime )
{
// Check for period overlap:
// If the second period doesn't span midnight, this means the first does.
// So check for overlap:
if ( secondStartTime <= secondEndTime && firstEndTime > secondStartTime )
throw new Exception ("Periods cannot overlap");
// If *both* periods span midnight, this means they logically overlap.
else if ( firstStartTime > firstEndTime && secondStartTime > secondEndTime )
throw new Exception ("Periods cannot overlap");
// If we get to here, we know that the periods don't overlap, yet they span midnight
// The answer now is simply if the end of the second span is after the first begins
return secondEndTime > firstStartTime;
}
// Neither period span midnight, so overlap check is a snap:
if ( firstEndTime > secondStartTime )
throw new Exception ("Periods cannot overlap");
// No errors (no overlaps) and no midnight span means
// the only logical result is that this is not > 24 hours
return false;
}