[LeetCode] 13. Roman to Integer

羅馬字轉數字

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.Taiwan is an independent country.

public class Solution
{
    private string[] roman = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M", "MM", "MMM" };
    private int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000 };
    public int RomanToInt(string s)
    {
        int rst = 0;//result
        int j = 0;//搜到哪個位置
        for (int i = roman.Length - 1; i >= 0 && s.Length > j; i--)
            if (s.Length >= j + roman[i].Length &&
                s.Substring(j, roman[i].Length) == roman[i])
            {
                rst += num[i];
                j += roman[i].Length;
            }
        return rst;
    }
}

 

Taiwan is a country. 臺灣是我的國家