diff --git a/19_counting_sundays/counting_sundays_test.go b/19_counting_sundays/counting_sundays_test.go new file mode 100644 index 0000000..2de6fbc --- /dev/null +++ b/19_counting_sundays/counting_sundays_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "testing" +) + +func Test_calWeek(t *testing.T) { + type args struct { + year int + month int + day int + } + tt := []struct { + name string + args args + want int + }{ + { + "1900-01-01", + args{ + 1900, + 01, + 01, + }, + 1, + }, + { + "2020-10-19", + args{ + 2020, + 10, + 19, + }, + 1, + }, + { + "2020-10-21", + args{ + 2020, + 10, + 21, + }, + 3, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := calWeek(tc.args.year, tc.args.month, tc.args.day) + if got != tc.want { + t.Errorf("calWeek = %d, want %d", got, tc.want) + } + }) + } +} + +func Test_isLeapYear(t *testing.T) { + tt := []struct { + name string + input int + want bool + }{ + { + "1900", + 1900, + false, + }, + { + "2000", + 2000, + true, + }, + { + "2020", + 2020, + true, + }, + { + "2021", + 2021, + false, + }, + { + "1800", + 1800, + false, + }, + { + "1600", + 1600, + true, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := isLeapYear(tc.input) + if got != tc.want { + t.Errorf("isLeapYear(%d) = %v, want %v", tc.input, got, tc.want) + } + }) + } +} diff --git a/19_counting_sundays/main.go b/19_counting_sundays/main.go new file mode 100644 index 0000000..b181fb5 --- /dev/null +++ b/19_counting_sundays/main.go @@ -0,0 +1,34 @@ +package main + +import "fmt" + +func main() { + sum := 0 + for y := 1901; y <= 2000; y++ { + for m := 1; m <= 12; m++ { + if calWeek(y, m, 1) == 0 { + sum++ + } + } + } + fmt.Println("sum:", sum) +} + +func calWeek(y, m, d int) int { + //w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1 + // + //公式中的符号含义如下,w:星期;c:世纪;y:年(两位数); + // m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算, + // 比如2003年1月1日要看作2002年的13月1日来计算);d:日;[ ]代表取整,即只要整数部分。 + if m == 1 || m == 2 { + y-- + m += 12 + } + c := y / 100 + y = y - c*100 + return (y + y/4 + c/4 - 2*c + 26*(m+1)/10 + d - 1) % 7 +} + +func isLeapYear(year int) bool { + return year%400 == 0 || (year%4 == 0 && year%100 != 0) +}