Leetcode 13. Roman to Integer

Roman to Integer
image 26

Roman to Integer

Roman to Integer : 把羅馬數字轉換成阿拉伯數字,並告訴我們一些規則(4:IV,9:IX),

個位數上出現4或者9時,左邊的羅馬數字一定要比右邊,減去這個羅馬數字對應的阿拉伯數字,其餘就正常相加即可。

Python

class Solution(object):
    def romanToInt(self, s):
        roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}        #給定一個羅馬轉換數值的對照dictionary
        ans=0
        for i in range(len(s)): 

           #左邊的羅馬數字一定要比右邊的小,減去這個羅馬數字對應的阿拉伯數字
            if i<len(s)-1 and roman[s[i]]<roman[s[i+1]]:  
                ans-=roman[s[i]]
            else:              #其餘正常相加
                ans+=roman[s[i]]
        return ans

C++

map紀錄Roman數字,先把各個對應Roman符號的值累加進ans,再比較左邊Roman符號的值是否大於右邊Roman符號的值,如果大於則從ans扣除,最後返回ans

class Solution {
public:
  int romanToInt(string s) {
    map<char, int> Roman{{'I', 1}, {'V', 5}, 
                     {'X', 10}, {'L', 50},
                     {'C', 100}, {'D', 500},
                     {'M', 1000}};
    int ans = 0;
    for (int i = 0; i < s.length(); i++) {
      ans += Roman[s[i]];
      if (i > 0 && Roman[s[i]] > Roman[s[i - 1]])
        ans -= 2 * Roman[s[i - 1]];
    }
    return ans;
  }
};