๐ŸŒŸ Converting Roman Numerals to Integer n vice-versa

๐ŸŒŸ Converting Roman Numerals to Integer n vice-versa

ยท

2 min read

These problems appeared in leecode and featured in various blogs, i have just summarised and included them using ts-problems deck.

๐Ÿ”– Roman Numerals to Integer conversion

Numbers generally increase in a roman numeral notation from right to left, any subtractive number must also be smaller than our current res.

So we can avoid the need for an extra variable here. We do run into the case of repeated numerals causing an issue III, but we can clear that by multiplying num by any number between 2 and 4 before comparing it to res, since the numerals jump in value by 5x.

Once we know how to properly identify a subtractive numeral, it's a simple matter to just iterate in reverse through given numeral to find and return the res.

function romanToInt(s: string): number {
  let res: number = 0;
  const symbols = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000,
  };
  s.split("")
    .reverse()
    .forEach((char) => {
      let val: number = parseInt(symbols[char]);
      if (res > 4 * val) {
        res -= val;
      } else {
        res += val;
      }
    });
  return res;
}

๐Ÿ”– Integer to Roman Numerals conversion

This solution uses a lookup table composed which can help in easier conversion and much simple compared to the above one.

function intToRoman(num: number): string {
  let res:string = "";
  const value:number [] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  const numerals:string [] = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
  for (let i = 0; num; i++)
    while (num >= value[i]){
        res += numerals[i];
         num -= value[i];
    }
  return res;
}

Here I have tried to solve them in typescript using ts-problems repo.

๐ŸŽ‰ Thanks for supporting! ๐Ÿ™

Would be great if you like to โ˜• Buy Me a Coffee, to help boost my efforts.

๐Ÿ” reposted at ๐Ÿ”— dev @aravindvcyber

๐Ÿ” reposted at ๐Ÿ”— medium @aravindvcyber

Did you find this article valuable?

Support Aravind V by becoming a sponsor. Any amount is appreciated!

ย