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

1 Answer

0 votes
function findNextDigit(num: number, target: number): number {
  let next: number = -1;

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

    if (current === target) {
      return next;
    }

    next = current;
  }

  return -1;
}

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

const result: number = findNextDigit(num, target);

if (result !== -1) {
  console.log(`The digit after ${target} in ${num} is ${result}.`);
} else {
  console.log(`The digit ${target} is not found or has no next digit in ${num}.`);
}
 
 
 
/*
run:
 
"The digit after 2 in 8902741 is 7." 
 
*/
  
  

 



answered Oct 18, 2025 by avibootz
...