[leetcode] 13. Roman to Integer

題目鏈接:https://leetcode.com/problems/roman-to-integer/

Given a roman numeral, convert it to an integer.

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

思路

羅馬數字總共有七個 即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。其數字之間可以組合來表示任意的數字,但是不可以進行運算。

其組合規律如下:

左加右減:

  1. 較大的羅馬數字右邊記上較小的羅馬數字,表示大數加小數

  2. 較大的羅馬數字左邊記上較小的羅馬數字,表示大數減小數

  3. 左減的數字只限於I、X、C

  4. 左減時不可以跨位,如果99不可以寫成IC,只能寫成XCIX

  5. 左減只能有一位。如8寫成VIII,而非IIX

  6. 右加最多三位。如14寫成XIV,而非XIIII

OK,基本的規則就這些。

    class Solution {  
    public:  
        int romanToInt(string s) {  
            hash['I'] = 1;  
            hash['V'] = 5;  
            hash['X'] = 10;  
            hash['L'] = 50;  
            hash['C'] = 100;  
            hash['D'] = 500;  
            hash['M'] = 1000;  
            int cnt = 0;  
            for(int i =0; i< s.size(); i++)  
            {  
                cnt += hash[s[i]];  
                if(i>0 && hash[s[i]] > hash[s[i-1]])  
                    cnt -= 2* hash[s[i-1]];  
            }  
            return cnt;  
        }  
    private:  
        unordered_map<char, int> hash;  
    };  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章