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

1 Answer

0 votes
/**
 * Represents the result of finding
 * the smallest and largest digits.
 */
interface MinMaxResult {
    min: number;
    max: number;
}

/**
 * Finds the smallest and largest digits in a number.
 *
 * @param number Input number.
 * @returns An object containing the smallest and largest digits.
 */
function findMinMaxDigits(number: number): MinMaxResult {
    // Handle negative numbers
    number = Math.abs(number);

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

    let minDigit: number = 9;
    let maxDigit: number = 0;

    while (number > 0) {
        // Extract the last digit
        const digit: number = 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 num: number = 839516;

// Find smallest and largest digits
const result: MinMaxResult = findMinMaxDigits(num);

// Display results
console.log(`Number: ${num}`);
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
...