---
id: 69f8c998d78ad3171a0713ba
title: "Challenge 287: Roman Numeral Fixer"
challengeType: 28
dashedName: challenge-287
---

# --description--

Given a string of malformed Roman numerals, return the value in standard Roman numeral notation.

The input will only use additive notation, so each symbol adds its value to the total. As a reminder, here are the symbols and values:

| Symbol | Value |
| ------ | ----- |
| `"I"`  | 1     |
| `"V"`  | 5     |
| `"X"`  | 10    |
| `"L"`  | 50    |
| `"C"`  | 100   |
| `"D"`  | 500   |
| `"M"`  | 1000  |

When re-encoding, use the largest possible symbol at each step, using subtractive pairs (`"IV"`, `"IX"`, `"XL"`, `"XC"`, `"CD"`, `"CM"`) where needed.

# --hints--

`fixNumerals("XIIIII")` should return `"XV"`.

```js
assert.equal(fixNumerals("XIIIII"), "XV");
```

`fixNumerals("IIIILX")` should return `"LXIV"`.

```js
assert.equal(fixNumerals("IIIILX"), "LXIV");
```

`fixNumerals("XXVVVIIIII")` should return `"XL"`.

```js
assert.equal(fixNumerals("XXVVVIIIII"), "XL");
```

`fixNumerals("MDCCLXXXXVIIII")` should return `"MDCCXCIX"`.

```js
assert.equal(fixNumerals("MDCCLXXXXVIIII"), "MDCCXCIX");
```

`fixNumerals("IIIIVVVVXXXXLLLLCCDD")` should return `"MCDLXIV"`.

```js
assert.equal(fixNumerals("IIIIVVVVXXXXLLLLCCDD"), "MCDLXIV");
```

`fixNumerals("ILCDMIVDIIXLCVCXDL")` should return `"MMCMLXXXIV"`.

```js
assert.equal(fixNumerals("ILCDMIVDIIXLCVCXDL"), "MMCMLXXXIV");
```

# --seed--

## --seed-contents--

```js
function fixNumerals(str) {

  return str;
}
```

# --solutions--

```js
function fixNumerals(str) {
  const values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
  const encoding = [
    [1000, "M"], [900, "CM"], [500, "D"], [400, "CD"],
    [100, "C"], [90, "XC"], [50, "L"], [40, "XL"],
    [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]
  ];

  let total = [...str].reduce((sum, c) => sum + values[c], 0);

  let result = "";
  for (const [value, symbol] of encoding) {
    while (total >= value) {
      result += symbol;
      total -= value;
    }
  }
  return result;
}
```
