You are given the following information,but you may prefer to do some
research for yourself.1 Jan 1900 was a Monday.
Thirty days has September,April,June and
November.All the rest have thirty-one,Saving February alone,Which
has twenty-eight,rain or shine. And on leap years,twenty-nine.A leap year occurs on any year evenly divisible by 4,but not on a
century unless it is divisible by 400.How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
我认为使用PHP可以轻而易举,因为它有很多内置的时间和日期功能.我的代码非常简单,所以我很难看到我在做什么这是错的.
我的代码:
<?PHP echo "<pre>"; $sunday_count = 0; for( $year = 1901; $year <= 2000; $year++ ) { for( $month = 1; $month <= 12; $month++ ) { // Produces a date in format: 1/1/2000 $date = $month . "/1/" . $year; $time = strtotime( $date ); $is_sunday = ( date( 'l',$time ) == "Sunday" ); echo "$date " . ( $is_sunday ? 'was a Sunday. ' : '' ) . "<br>"; if( $is_sunday ) $sunday_count++; } } echo "Answer: $sunday_count"; echo "</pre>"; ?>
编辑1
解决方案应该是171.
使用Wolfram Alpha和我的Windows时钟,我加倍检查了我的代码报告的几个星期日.所有人都检查好了.
因此,似乎我的代码报告了有效和合法的星期日,但不知何故,它已经错过了其中的两个.
编辑2
我对代码中日期的格式进行了以下微小更改:
$date = sprintf('%d-%02d-01',$year,$month); // formats yyyy-mm-dd
然后我使用@ MadaraUchiha的代码生成一个包含171个正确日期的数组.
在将他的约会与我的比较后,这两个错过的日期:
1901-09-01
1901-12-01
编辑3
Codepad also shows这些日期不是星期日(但它们确实应该是).
并且我确定日期被正确地解释为YYYY-MM-DD,因为我的代码提供给解决方案的日期之一是2000-10-01,如果10是月份,那将只是星期日,而不是一天.
编辑4
显然,如果在32位系统上,Unix时间戳将无法在该范围之外工作:
Fri,13 Dec 1901 20:45:54 GMT
至
Tue,19 Jan 2038 03:14:07 GMT
64位系统具有更大的整数,这使得范围更大(在PHP中).