DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for 🌟 Converting Roman Numerals to Integer n vice-versa
Aravind V
Aravind V

Posted on • Updated on • Originally published at devpost.hashnode.dev

🌟 Converting Roman Numerals to Integer n vice-versa

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;
}
Enter fullscreen mode Exit fullscreen mode

πŸ”– 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;
}
Enter fullscreen mode Exit fullscreen mode

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

πŸ” original post at πŸ”— Dev Post

Thanks for supporting! πŸ™

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

Top comments (0)

🀯

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs