码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Roman to Integer

时间:2015-02-05 18:19:42      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[LeetCode] Roman to Integer

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4275384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!