发出修剪循环结果中的最后一个字的问题

时间:2019-01-25 21:38:23

标签: php

我正在玩HackerRank练习,这应该是结果:

61 then 62 then 63 then 64 then 65 then 66 then 67 then 68 then 69 then 70

但是我在then之后得到了70

<?php

function countUp($start) {

    for ($i = 61; $i <= 70; $i++) {
        echo $i . " then ";
    }

}

$start = intval(trim(fgets(STDIN)));

countUp($start);

我在做什么错?谢谢。

编辑:我尝试过:

echo "61"; 
for ($i = 62; $i <= 70; $i++) {
    echo " then ".$i;
}

但是测试用例给了我错误:

enter image description here

如果您想尝试:https://www.hackerrank.com/tests/ioa3k1bq

4 个答案:

答案 0 :(得分:2)

单线:

echo implode(' then ', range($n = intval(file_get_contents('php://stdin')), $n+9));

答案 1 :(得分:1)

我已经通读了您的考试不及格。我希望这对您有用。

<?php>

function countUp($start) {

  $FIRST_NUM = $start + 1;
  $LAST_NUM = $start + 10;

    for ($i = $FIRST_NUM; $i <= $LAST_NUM; $i++) {

        if($i == $LAST_NUM) {echo $i; break;}

        echo $i . " then ";
    }

}
$start = intval(trim(fgets(STDIN)));
countUp($start);  // try countUp(60); to test this

答案 2 :(得分:0)

像这样使用:

<?php

function countUp($start) {

    for ($i = 61; $i <= 70; $i++) {
        $txt.= $i . " then ";
    }
  $str= preg_replace('/\W\w+\s*(\W*)$/', '$1', $txt);
  echo $str
}

$start = intval(trim(fgets(STDIN)));

countUp($start);

答案 3 :(得分:-1)

您应该检查何时打印了最后一个号码,并打印该号码而无需再输入“然后”

for ($i = 61; $i <= 70; $i++) {
    echo $i;
    if($i <= 69)
        echo " then ";
}

另一个解决方案可以使用数组启用爆破(http://php.net/manual/en/function.implode.php

$numbs = [];
for ($i = 61; $i <= 70; $i++) {
    array_push($numbs, $i);
}
return implode(" then ", $numbs);