Given a roman numeral, convert it to an integer.

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

 

思路:从各位向前处理,当前字符代表的数比后面一位字符代表的数大(包括等于),就加,小就减。

class Solution {
    public:  
        int romanToInt(string s)  
        {        // Note: The Solution object is instantiated only once and is reused by each test case.
            int result=0;    
            map<char,int> roman;  
            roman['I']=1;   
            roman['V']=5; 
            roman['X']=10;   
            roman['L']=50; 
            roman['C']=100;    
            roman['D']=500;   
            roman['M']=1000;   
            for(int i=s.length()-1;i>=0;i--)    
            {    
                if(i==s.length()-1)   
                {    
                    result=roman[s[i]];    
                    continue;
                }   
                if(roman[s[i]] >= roman[s[i+1]])    
                    result+=roman[s[i]];    
                else  
                    result-=roman[s[i]];    
            }   
            return result;  
        }   
};

 

相关文章:

  • 2021-11-22
  • 2022-02-19
  • 2021-12-29
  • 2021-12-29
  • 2021-09-17
  • 2021-09-06
猜你喜欢
  • 2021-12-31
  • 2022-02-15
  • 2021-07-08
  • 2022-12-23
  • 2021-05-22
  • 2022-02-12
  • 2021-11-24
  • 2021-12-28
相关资源
相似解决方案