Roman To Integer

Given a roman numeral, convert it to an integer.

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

https://leetcode.com/problems/roman-to-integer/

Discussion

首先要确定一下interger的范围,并要问清楚基本Roman number跟interger的对应关系。
从前往后扫描,用一个临时变量记录分段数字。

  • 如果当前比前一个大,说明这一段的值应该是当前这个值减去上一个值。比如IV = 5 – 1
  • 否则,将当前值加入到结果中,然后开始下一段记录。比如VI = 5 + 1, II=1+1

Solution

inline int c2n(char c) {  
     switch(c) {  
       case 'I': return 1;  
       case 'V': return 5;  
       case 'X': return 10;  
       case 'L': return 50;  
       case 'C': return 100;  
       case 'D': return 500;  
       case 'M': return 1000;  
       default: return 0;  
      }  
    }  
    int romanToInt(string s) {  
      // Start typing your C/C++ solution below  
      // DO NOT write int main() function  
      int result=0;  
      for(int i =0; i< s.size(); i++)  
      {  
        if(i>0&& c2n(s[i]) > c2n(s[i-1]))  
        {  
          result +=(c2n(s[i]) - 2*c2n(s[i-1]));  
        }  
        else  
        {  
          result += c2n(s[i]);  
        }  
      }  
      return result;  
    }

Solution by hash rather than the inlline function

// Time:  O(n)
// Space: O(1)

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

About inline function

results matching ""

    No results matching ""