class DigitFinder
{
/**
* Finds the digit that comes before the target digit when scanning from right to left.
*/
public static function findPreviousDigit(int $number, int $target): int
{
while ($number > 0) {
$current = $number % 10;
$number = intdiv($number, 10);
if ($current === $target) {
return $number > 0 ? $number % 10 : -1;
}
}
return -1;
}
}
$number = 8902741;
$target = 7;
$result = DigitFinder::findPreviousDigit($number, $target);
if ($result !== -1) {
echo "The digit before {$target} in {$number} is {$result}." . PHP_EOL;
} else {
echo "The digit {$target} is not found or has no previous digit in {$number}." . PHP_EOL;
}
/*
run:
The digit before 7 in 8902741 is 2.
*/