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

Each digit differs from the next one by 1

Script has to work this way:

isJumping(9) === 'JUMPING'

This is a one digit number

isJumping(79) === 'NOT JUMPING'

Neighboring digits do not differ by 1

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

isJumping(23454) === 'JUMPING'

Neighboring digits differ by 1

I have:

function isJumping(number) {
    let str = number.toString();
    for (let i = 1; i < str.length; i++) {
        if (Math.abs(str[i+1]) - Math.abs(str[i]) == 1){
            return 'JUMPING';
        }
    }
    return 'NOT JUMPING';
}
console.log(isJumping(345));

Help please, where is mistake?

>Solution :

Loop over the characters and early return with "NOT JUMPING" if the condition is violated & if the condition is never violated return "JUMPING".

function isJumping(num) {
  const strNum = String(Math.abs(num));

  for (let i = 0; i < strNum.length - 1; i++) {
    if (Math.abs(strNum[i] - strNum[i + 1]) > 1) {
      // replace `> 1` with `!== 1`, if diff 0 is not valid!
      return "NOT JUMPING";
    }
  }

  return "JUMPING";
}

console.log(isJumping(9));
console.log(isJumping(79));
console.log(isJumping(23454));
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