Roman to Integer

Roman to Integer 

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution:

一種很粗暴的解法,羅列所有可能出現的情況:
class Solution {
public:
    int romanToInt(string s) {
        int total = 0;
        for (int a = 0; a < s.length(); a++)
        {
            if (s[a] == 'I')
            {
                if (s[a+1] == 'V')
                {
                    total += 4;
                    a++;
                }
                else if (s[a+1] == 'X')
                {
                    total += 9;
                    a++;
                }
                else
                {
                    total += 1;
                }
            }
            else if (s[a] == 'X')
            {
                if (s[a+1] == 'L')
                {
                    total += 40;
                    a++;
                }
                else if (s[a+1] == 'C')
                {
                    total += 90;
                    a++;
                }
                else
                {
                    total += 10;
                }
            }
            else if (s[a] == 'C')
            {
                if (s[a+1] == 'D')
                {
                    total += 400;
                    a++;
                }
                else if (s[a+1] == 'M')
                {
                    total += 900;
                    a++;
                }
                else
                {
                    total += 100;
                }
            }
            else if (s[a] == 'V') total += 5;
            else if (s[a] == 'L') total += 50;
            else if (s[a] == 'D') total += 500;
            else if (s[a] == 'M') total += 1000;
        }
        return total;
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章