我正在研究Euler问题19,其内容如下:
你会得到以下信息,但你可能更愿意为自己做一些研究。1900年1月1日是星期一。 30天是9月份, 4、6月份和November.所有的年份都有31天,仅 Saving 2月一天,有28天,雨水或shine.,在闰年,20-9, a闰年发生在任何一年都可以被4整除,但除非它可以被400整除,否则不能在一个世纪内发生。在二十世纪的第一个星期日(1901年1月1日至2000年12月31日)有多少个星期日?
请注意,我的标题有点误导,因为这不包括20世纪的所有星期日,只是那些落在这个月的第一天。
这是我的密码:
public int HowManySundays()
{
// Have an array with the number of days in each month. For example, month 0 is January,
// which has 31 days.
int[] daysInEachMonth = new int[]
{
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};
int currentYear = 1900;
// First year in 1900
// We could calculate the first Sunday in 1901 to save a little time
// but that's not all *that* much of an optimization so it's not terribly important
int currentDay = 7;
int currentMonth = 0;
int numberOfSundays = 0;
while (currentYear < 2001)
{
// Add 7 each time so that we know that it's another Sunday
currentDay += 7;
// I don't particularly like the special reasoning for February for leap-year detection
// We don't actually have to do separate logic for centuries because the only century we
// care about is the year 2000, which we already know is evenly divisible by 400
int daysInMonth =
currentMonth == 1 ?
((currentYear % 4 == 0) ? 29 : 28) :
daysInEachMonth[currentMonth];
if (daysInEachMonth[currentMonth] < currentDay)
{
currentDay -= daysInEachMonth[currentMonth];
currentMonth++;
// Months are 0 - 11
// See if we've wrapped around to a new year
if (currentMonth >= 12)
{
currentMonth = 0;
currentYear++;
}
// If day == 1, then it must be a Sunday on the first day of the month
if (currentDay == 1 && currentYear > 1900)
{
numberOfSundays++;
}
}
}
return numberOfSundays;
}我有一个简单的单元测试(这里不包括),证明我的方法确实返回了正确的答案(171)。
有没有人对此有反馈(尤其是它的可读性)?这是非常有效的,还是我错过了一些优化?
发布于 2017-08-14 20:41:42
您的逻辑是检查月、跃年和相关日期逻辑中的天数。
下面的片段就行了。这个逻辑将在20世纪的每个月(1到12)循环,并检查月的第一天是否是星期日。
var result = 0;
for(int year = 1901; year <= 2000; year++)
{
for(int month = 1;month<=12;month++)
{
if (new DateTime(year, month, 1).DayOfWeek == DayOfWeek.Sunday)
result++;
}
}
Console.WriteLine(result);https://codereview.stackexchange.com/questions/172995
复制相似问题