I have asked to make a function that have two parameters, start number and the end number and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive!

The start number will always be smaller than the end number. Both numbers can be also negative! The end number may be a very big integer value like 10^9

any suggestions?

1

There are 1 best solutions below

2
Nigel Ren On

You have a couple of problems in you current code. The first is as pointed out, just dividing a number by 10 causes the number to start having decimal places. This means it will almost always be > 0.

SO you could change that to use floor to round it down...

$num = floor($num / 10);

The other problem you have is in your comparison -

if ($num != 5 || !isDigitPresent($num, 5))

With or (||) as soon as it finds a true value, it stops checking the rest of the condition (as the result will still be true), so the isDigitPresent() will not be called if $num is != 5 (which is most of the time.) So this should be shortened to

if (!isDigitPresent($num, 5))

There are all sorts of alternatives to this, but based on what you doing you could use...

$count = 0;
$digit = 5;
// range() generates an array with the values instead of writing your own
foreach (range(4, 17) as $num) {
    // Check if the digit is any of the characters in the string representation
    if (in_array($digit, str_split($num))) {
        echo $num . PHP_EOL;
    } else {
        $count++;
    }
}
echo 'not containg digit:' . $count;