几分钟应该解决的小问题……我依旧做了很久……算了……告诉自己慢慢来~
这次犯的错误
- 题目数据看错了 1900年写成了1999年……
- 额……我把c里面的 = 和 == 再次使用混乱……
第二个错误真是不可饶恕……
#include <stdio.h>
int
leap(year)
{
if ((year % 100 == 0) && (year % 400 == 0))
return 1;
if ((year % 100 != 0) && (year % 4 == 0))
return 1;
return 0;
}
int M[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int
main()
{
int y, m, d, week = 0, ans = 0, monthDay;
//force to count
for (y=1900; y < 2001; y++)
{
for (m=1; m < 13; m++)
{
if (m == 2)
monthDay = 28 + leap(y);
else
monthDay = M[m];
for (d=0; d < monthDay; d++)
{
if ((d == 0) && (week == 6))
ans ++;
week = (week + 1) % 7;
}
}
}
//minus what i added during 1900
// problem is asking for from 1901 to 2001. so should minus the addtional part.
y = 1900;
for (m=1; m < 13; m++)
{
if (m == 2)
monthDay = 28 + leap(y);
else
monthDay = M[m];
for (d=0; d < monthDay; d++)
{
if ((d == 0) && (week == 6))
ans --;
week = (week + 1) % 7;
}
}
printf("%d", ans);
}
比较简单。我在判断
if ((d == 0) && (week == 6))
这句……写错了……真是难以释怀……啊~蛋碎了
看看jason大牛写的……
用了Gaussian algorithm to determine day of week
这是非常明智的做法~不用一步一步运算了~
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day_of_week(int year, int month, int day) {
// Using the Gaussian algorithm
int d = day;
double m = (double) ((month - 3) % 12 + 1);
int Y;
if(m > 10) Y = year - 1;
else Y = year;
int y = Y % 100;
int c = (Y - (Y % 100)) / 100;
int w = ((d+(int)floor(2.6*m-0.2)+y+ y/4 + c/4 -2*c))%7;
return w;
}
long months_start_range(int day, int year_start, int year_end) {
unsigned long total = 0;
int year, month;
for(year = year_start; year < year_end; year++) {
for(month = 1; month <= 12; month++) {
if(day_of_week(year, month, 1)==day) total++;
}
}
return total;
}
int main(int argc, char **argv) {
int iter = 0;
long total;
while(iter < 100000) {
total = months_start_range(0,1901,2000);
iter++;
}
printf("Solution: %ld\n",total);
return 0;
}
代码风格习惯还是蛮不错的~嗯……突然发现我的多个code都少了 return 0!!!!