问题编码一个程序,该程序使一个数字与另一个数字的偶数数字相反但相反

Issue coding a program which makes a number with the even digits of an other number but backwards

我必须制作几个编码块,我被困在其中的 3 个。对不起,我的英语不好。

首先如总结所说。我试过了,它显示了偶数,但也显示了大量的“0”。

<?php

$n = 33421;
$m = "";

while ($n != 0) {
    if (($n % 2 == 0) && ($n / 10) != 0) {
        $temp = strval($n % 10);
        $m .= $temp;
    }
    $n = $n / 10;
}

echo $m;
?

我还有 2 件事要做,但不知道如何完成,希望有人能帮忙。

您显示代码的问题的解决方案 - 反转显示偶数位。

此代码首先使用 str_split() 将数字拆分为单独的元素,它采用字符串并将其拆分为单独的数字。然后对于每个数字,它检查它是否偶数并将其添加到结果的开头(反转数字)...

$n = 33421;
$m = "";

foreach ( str_split($n) as $digit ) {
    if ( $digit % 2 == 0 )  {
        $m = $digit.$m;
    }
}
echo $m;

另一种解决方案是使用正则表达式删除所有赔率数字,然后反转输出字符串。

$n = 33421;
$m = strrev(preg_replace("/[13579]/", "", $n));
echo $m; //24

类似于 str_split 和使用 preg_split 和 array_walk

的 foreach 解决方案
<?php
    /**
    * Split string into array
    * - walk the array and test values as multiples of 2
    * - pass $result by reference
    * - append $result after $value to reverse the resulting string
    */
    $number = 33421;
    $result = '';
    $arr = preg_split('//',$number,-1,PREG_SPLIT_NO_EMPTY);
    array_walk($arr, function(&$value) use (&$result) {
        if((int)$value % 2 == 0){
            $result = $value.$result; 
        }
    });
    echo $result;
?>