Home > Mobile >  Function to return a number in array in expanded form?
Function to return a number in array in expanded form?

Time:10-26

I've been stuck trying to create the function mentioned above for something I am working on

function expandedForm(num: number): number[] {
  // ...
}

const k = expandedForm(8571);
console.log(k);
// [ 8000, 500, 70, 1 ]

Searching for this online only finds functions which return a string with pluses between the numbers. Some help will be appreciated.

CodePudding user response:

You can manipulate the input using the remainder operator:

function expandedForm(num: number): number[] {
  const arr: number[] = [];
  
  var x = num;

  // Iterate until `x` is greater than zero
  //
  // For each iteration, keep track of the `i`:
  // First iteration,  i == 0, 10^i == 10^0 == 1
  // Second iteration, i == 1, 10^i == 10^1 == 10
  // Third iteration,  i == 2, 10^i == 10^2 == 100
  // This variable will let you know the current decimal place
  for (var i = 0; x > 0; i  ) {
    // Get the last digit of `x` by using the remainder operator
    const currentDigit = x % 10;

    // Insert to the array using the previous algorithm 
    arr.push(Math.pow(10, i) * currentDigit);

    // Remove the last digit of `x` using the floor of the division by 10
    x = Math.floor(x / 10);
  }

  // Reverse the array
  return arr.reverse();
}

const k = expandedForm(8571);
console.log(k);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Alternatively, you can insert to the first element of arr, without needing to reverse it in the end:

function expandedForm(num: number): number[] {
  const arr: number[] = [];
  
  var x = num;

  for (var i = 0; x > 0; i  ) {
    const currentDigit = x % 10;

    // Insert into the first element of `arr`
    arr.splice(0, 0, Math.pow(10, i) * currentDigit);

    x = Math.floor(x / 10);
  }

  // Just return the array
  return arr;
}

const k = expandedForm(8571);
console.log(k);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related