How to remove characters from a numeric string such that the string becomes divisible by 8 in PHP

1 Answer

0 votes
function checkIfNumExist($num, $s) {
    $index = 0;
    
    foreach (str_split($s) as $ch) {
        if ($num[$index] == $ch) {
            $index++;
            if (strlen($num) == $index) {
                break;
            }
        }
    }
    
    return $index == strlen($num) ? 1 : 0;
}

function convertStringToBecomesDivisibleBy8($s) {
    for ($i = 8; $i < 1000.0; $i += 8) {
        $num = strval($i);
        if (checkIfNumExist($num, $s) == 1) {
            return $num;
        }
    }
    
    return "-1";
}

$s1 = "127892";
$result = convertStringToBecomesDivisibleBy8($s1);
echo $result . "\n";

$s2 = "1201674";
$result = convertStringToBecomesDivisibleBy8($s2);
echo $result . "\n";

$s3 = "1209574";
$result = convertStringToBecomesDivisibleBy8($s3);
echo $result . "\n";

$s4 = "190395473";
$result = convertStringToBecomesDivisibleBy8($s4);
echo $result . "\n";

$s5 = "1309577";
$result = convertStringToBecomesDivisibleBy8($s5);
if (!(strcmp($result,"-1") == 0)) {
    $s5 = $result;
    echo $s5,"\n";
}
else {
    echo "No numeric characters combination divisible by 8" . "\n";
}



/*
run:

8
16
24
104
No numeric characters combination divisible by 8

*/

 



answered Mar 19, 2024 by avibootz
...