public int RomanToInt(string s)
{
if (s == null || s == string.Empty)
return 0;
Dictionary<string, int> dict = new Dictionary<string, int>();
int result = 0;
dict.Add("I", 1);
dict.Add("V", 5);
dict.Add("X", 10);
dict.Add("L", 50);
dict.Add("C", 100);
dict.Add("D", 500);
dict.Add("M", 1000);
dict.Add("IV", 4);
dict.Add("IX", 9);
dict.Add("XL", 40);
dict.Add("XC", 90);
dict.Add("CD", 400);
dict.Add("CM", 900);
for (int i = 0; i < s.Length; i++)
if ((s[i] == 'I' || s[i] == 'X' || s[i] == 'C') && i < s.Length - 1 && dict.ContainsKey(s.Substring(i, 2)))
result += dict[s.Substring(i++, 2)];
else
result += dict[s[i].ToString()];
return result;
}
/*
// This application helps you convert roman numerals to numbers or vice-versa
*/
// First install the package @ "npm install cr-numeral"
// Then import or require the package in your application
const {
convertNumberToRoman: cnr,
convertRomanToNumber: crn,
} = require("cr-numeral");
// OR
const cnr = require("cr-numeral").convertNumberToRoman;
const crn = require("cr-numeral").convertRomanToNumber;
// Define your variables
const number = 2021;
const numeral = "MMMXXV"; // Case-insensitive
// Use your package/module
const toRoman = cnr(number);
const toNumber = crn(numeral);
// Log or use your result
console.log(toRoman, toNumber);
// Converting a number to Roman Numeral
const { convertNumberToRoman } = require('cr-numeral');
// OR
const convertNumberToRoman = require('cr-numeral').convertNumberToRoman;
convertNumberToRoman(2021));
"MMXXI"
convertNumberToRoman(-2021)); // Can not convert a negative number or zero
"Can not convert Zero or negative numbers!!!"
convertNumberToRoman("na256m"));
"You must provide only valid numbers!!!"
convertNumberToRoman(false));
"Cannot use Boolean values!!!"
convertNumberToRoman(true));
"Cannot use Boolean values!!!"
// Converting Roman Numeral to Number
const { convertRomanToNumber } = require('cr-numeral');
// OR
const convertRomanToNumber = require('cr-numeral').convertRomanToNumber;
convertRomanToNumber("MMXXI"));
"2021"
convertRomanToNumber("na256m"));
"Provide a valid roman character!!!"
"Cause these are invalid roman numerals : [ N,A,2,5,6 ]"
convertRomanToNumber(6355));
"You must provide only valid strings!!!"
convertRomanToNumber(false));
"Cannot use Boolean values!!!"
convertRomanToNumber(true));
"Cannot use Boolean values!!!"
// With love @kouqhar