[LeetCode] Roman to Integer

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;  
        }   
};

 

posted @ 2015-02-05 17:24  穆穆兔兔  阅读(142)  评论(0编辑  收藏  举报