PHP看起来顺序

时间:2017-10-29 11:31:08

标签: php arrays foreach

我正在尝试用PHP编写Conway外观和说法序列。 这是我的代码:

function look_and_say ($number) {
    $arr = str_split($number . " ");
    $target = $arr[0];
    $count = 0;
    $res = "";
    foreach($arr as $num){
        if($num == $target){
            $count++;
        }else{
            $res .= $count . $target;
            $count = 1;
            $target = $num;
        }        
    }
    return $res;
}

当我运行该功能时,look_and_say(9900)我获得了预期的价值:2920。 我的问题是将$arr指定为$arr = str_split($number)而不是$arr = str_split($number . " "),结果会省略$arr的最后一个元素并返回29

$arr foreach的末尾添加空格以检查最后一个元素是否正常或者是否有更好的方法来练习此代码 - 除了正则表达式之外。

2 个答案:

答案 0 :(得分:1)

我有两种方法可以想出来。

1是在循环之后的结果中添加连接。

function look_and_say ($number) {
    $arr = str_split($number);
    $target = $arr[0];
    $count = 0;
    $res = "";
    foreach($arr as $num){
        if($num == $target){
            $count++;
        }else{
            $res .= $count . $target;
            $count = 1;
            $target = $num;
        }        
    }
    $res .= $count . $target;
    return $res;
}

第二个是在循环中添加另一个if子句并确定最后一次迭代:

function look_and_say ($number) {
    $arr = str_split($number);
    $target = $arr[0];
    $count = 0;
    $res = "";
    $i=0;
    $total = count($arr);
    foreach($arr as $num){        
        if($i == ($total-1))
        {
            $count++;
            $res .= $count . $target;
        }
        elseif($num == $target){
            $count++;
        }else{
            $res .= $count . $target;
            $count = 1;
            $target = $num;
        }
        $i++;
    }
    return $res;
}

答案 1 :(得分:1)

我想建议您使用两个嵌套while循环的其他方式:

<?php

function lookAndSay($number) {
    $digits = str_split($number);
    $result = '';
    $i = 0;
    while ($i < count($digits)) {
        $lastDigit = $digits[$i];
        $count = 0;
        while ($i < count($digits) && $lastDigit === $digits[$i]) {
            $i++;
            $count++;
        }
        $result .= $count . $lastDigit;
    }

    return $result; 
}