Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to create a function that takes ANY number and finds the LARGEST number formed by consecutive digits in that number

how to create a function that takes ANY number and finds the LARGEST number formed by consecutive digits in that number in Javascript ?

example:
input: 90123609789
output: 90123

input: 53590 output 90
input:674030098567819 output: 5678

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try all substrings where the difference between adjacent digits is 1 under modulus 10.

function largestConsecutiveDigits(n) {
  let str = String(n),
    res = Math.max(...str);
  for (let i = 0; i < str.length; i++) {
    for (let j = i + 1; j < str.length; j++) {
      if ((str[j] - str[j - 1] + 10) % 10 === 1) 
        res = Math.max(res, str.slice(i, j + 1));
      else break;
    }
  }
  return res;
}
console.log(largestConsecutiveDigits('90123609789'));
console.log(largestConsecutiveDigits('53590'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading