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

1 Answer

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

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

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

    next = current;
  }

  return -1;
}

const number = 8902741;
const target = 2;

const result = findNextDigit(number, target);

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

 
 
/*
run:
 
The digit after 2 in 8902741 is 7.
 
*/

 



answered Oct 18, 2025 by avibootz
...