Coding Challenge Practice – Question 69

The task is to create a function to return the n-th number string in a sequence. n starts from 1.

The boilerplate code

function getNthNum(n) {
  // your code here
}

Start with the first number

if(n === 1) return "1";

To get the next number, describe the digits of the previous ones. Count how many times the same digits appear one after the other. When it changes to a new digit, write the count down and the digit being counted.

let result = "1";

  for (let i = 2; i <= n; i++) {
    let current = "";
    let count = 1;

    for (let j = 1; j <= result.length; j++) {
      if (result[j] === result[j - 1]) {
        count++;
      } else {
        current += count.toString() + result[j - 1]; 
        count = 1;
      }
    }

    result = current;
  }

After repeating the process n times, return the final string.

return result

The final code:

function getNthNum(n) {
  // your code here
  if(n === 1) return "1";

  let result = "1";

  for(let i = 2; i <= n; i++) {
    let current = "";
    let count = 1;

    for(let j = 1; j <= result.length; j++) {
      if(result[j] === result[j - 1]) {
        count++
      } else {
        current += count.toString() + result[j - 1];
        count = 1;
      }
    }
    result = current;
  }
  return result;
}

That’s all folks!

Similar Posts