2

As part of a Roman numerals converter algorithm, I would like to break a given number into their digit values. What I precisely want to do is as follows:

1984 = 1000+900+80+4

It would be better to let you know where I will use the outcome. I will push the result in an array and match with their Roman numeral counterpart, e.g. 1000 = M, 900 = CM, 80 = LXXX, 4 = IV.

1984 = MCMLXXXIV

What kind of function is needed to produce the expected output?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • apparently you can use this https://blog.usejournal.com/create-a-roman-numerals-converter-in-javascript-a82fda6b7a60 – jaswanth Apr 20 '20 at 15:05
  • My methodology differs from most of the others on the web, but this could also be a great use. – Mehmet Eyüpoğlu Apr 20 '20 at 15:09
  • ok got it for the first part you can try this `a=1984;a1=String(a).split("").map((x, i)=>{return parseInt(x+"0".repeat(jash.length-i-1))})` – jaswanth Apr 20 '20 at 15:19
  • https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript – epascarello Apr 20 '20 at 15:40
  • Does this answer your question? [Convert a number into a Roman Numeral in javaScript](https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript) – Brian Tompsett - 汤莱恩 Apr 25 '20 at 08:13

2 Answers2

1

Here are two small algorithms to do just that:

function separate(number) {
  const length = number.toString().length;
  const result = [0];
  let step = 1;

  for (let i= 0; i< length; i++) {
    step *= 10;
    let part = number % step;

    result.forEach(previous => {
      part -= previous;
     });

    result[i] = part;
  }

  return result;
}

and

function separate(number) {
  const str = number.toString();
  const result = [];

  for (var i = 0; i < str.length; i++) {
    result[i] = str.charAt(i) * Math.pow(10, i);
  }

  return result;  
}

It returns an array with each separated number

alexortizl
  • 2,125
  • 1
  • 12
  • 27
1

I tweaked it into this one-liner:

Array.from((1984).toString()).reverse().map((d, i) => d * 10 ** i)

This will give you the parts in reverse (least significant digit first); depending on your need you may want to add another .reverse() at the end.

Touffy
  • 6,309
  • 22
  • 28
  • let separator = (num) => { let array = Array .from((num).toString()) .reverse() .map((d, i) => d * 10 ** i) .sort((a,b) => b - a ) return array; } – Mehmet Eyüpoğlu Apr 20 '20 at 15:53
  • 1
    the `sort()` is overkill, you should just use `reverse()` : `let separator = num => Array.from(num.toString()).reverse().map((d, i) => d * 10 ** i).reverse()` – Touffy Apr 20 '20 at 15:58