How to convert a Roman number to an integer in TypeScript

1 Answer

0 votes
// Roman numeral to integer conversion in TypeScript

const romanMap: Record<string, number> = {
  I: 1,
  V: 5,
  X: 10,
  L: 50,
  C: 100,
  D: 500,
  M: 1000
};

function romanToInt(s: string): number {
  let total = 0;
  let prevValue = 0;

  // iterate backwards over the string
  for (let i = s.length - 1; i >= 0; i--) {
    const currentValue = romanMap[s[i]];
    if (currentValue < prevValue) {
      total -= currentValue;
    } else {
      total += currentValue;
    }
    prevValue = currentValue;
  }

  return total;
}

// main
const roman = "XCVII";
const result = romanToInt(roman);

console.log(`The integer value of ${roman} is ${result}`);


/*
XCVII =
XC+V+I+I =
90+5+1+1 =
97
*/


/*
run:

"The integer value of XCVII is 97" 

*/

 



answered Dec 3, 2025 by avibootz
...