加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Project Euler#19代码似乎正确.我错过了什么?

发布时间:2020-12-13 13:09:09 所属栏目:PHP教程 来源:网络整理
导读:问题19: 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
问题19:

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>";
?>

我的代码提出的解决方案是169,这是不正确的.任何的想法?

编辑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
它在某些使用时间戳的系统上可能不起作用的原因是32位系统上的Unix时间戳范围是从格林威治标准时间1901年12月13日20:45:54到格林威治标准时间2038年1月19日星期二03:14:07,所以你错过了第一年的几乎所有月份.

64位系统具有更大的整数,这使得范围更大(在PHP中).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读