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

1 Answer

0 votes
/**
 * Finds the smallest and largest digits in a number.
 *
 * @param {number} number - Input number.
 * @returns {{min: number, max: number}}
 */
function findMinMaxDigits(number) {
    // Handle negative numbers
    number = Math.abs(number);

    // Special case for 0
    if (number === 0) {
        return { min: 0, max: 0 };
    }

    let minDigit = 9;
    let maxDigit = 0;

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

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

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

        // Remove the last digit
        number = Math.floor(number / 10);
    }

    return {
        min: minDigit,
        max: maxDigit
    };
}

// Input data
const number = 839516;

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

// Display results
console.log(`Number: ${number}`);
console.log(`Smallest digit: ${result.min}`);
console.log(`Largest digit: ${result.max}`);


/*
run:

Number: 839516
Smallest digit: 1
Largest digit: 9

*/

 



answered 1 day ago by avibootz
...