How to find the smallest and largest digits in a number in PHP

1 Answer

0 votes
/**
 * Finds the smallest and largest digits in a number.
 *
 * @param int $number Input number.
 * @return array Associative array containing:
 *               - 'min' => smallest digit
 *               - 'max' => largest digit
 */
function findMinMaxDigits(int $number): array
{
    // Handle negative numbers
    $number = abs($number);

    // Special case for 0
    if ($number === 0) {
        return ['min' => 0, 'max' => 0];
    }

    $minDigit = 9;
    $maxDigit = 0;

    while ($number > 0) {
        // Extract the last digit
        $digit = $number % 10;

        // Update smallest digit
        if ($digit < $minDigit) {
            $minDigit = $digit;
        }

        // Update largest digit
        if ($digit > $maxDigit) {
            $maxDigit = $digit;
        }

        // Remove the last digit
        $number = intdiv($number, 10);
    }

    return [
        'min' => $minDigit,
        'max' => $maxDigit
    ];
}

// Input data
$number = 839516;

// Find smallest and largest digits
$result = findMinMaxDigits($number);

// Display results
echo "Number: {$number}\n";
echo "Smallest digit: {$result['min']}\n";
echo "Largest digit: {$result['max']}\n";


/*
run:

Number: 839516
Smallest digit: 1
Largest digit: 9

*/

 



answered 1 day ago by avibootz
...