'Roman to Integer' Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string s = "III";

    void Start()
    {
        Debug.Log(s + " => " + RomanToInt(s));
    }

    public int RomanToInt(string s)
    {
        var map = new Dictionary<char, int> { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };
        int num = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (i == 0 || map[s[i]] <= map[s[i - 1]])
            {
                num += map[s[i]];
            }
            else
            {
                num += map[s[i]] - 2 * map[s[i - 1]];
            }
        }
        return num;
    }
}