How to find the digit previous to a given digit in a number with TypeScript

1 Answer

0 votes
// Finds the digit that comes before the target digit when scanning from right to left.

function findPreviousDigit(num: number, target: number) {
    while (num > 0) {
        const current = num % 10;
        num = Math.floor(num / 10);

        if (current === target) {
            return num > 0 ? num % 10 : -1;
        }
    }

    return -1;
}

const num: number = 8902741;
const target = 7;

const result = findPreviousDigit(num, target);

if (result !== -1) {
    console.log(`The digit before ${target} in ${num} is ${result}.`);
} else {
    console.log(`The digit ${target} is not found or has no previous digit in ${num}.`);
}


/*
run:

"The digit before 7 in 8902741 is 2." 

*/

 



answered Oct 21, 2025 by avibootz
...