Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

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
...