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

【Roman To Integer】cpp

时间:2015-05-11 17:35:39      阅读:150      评论: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) {
        const int size = 7;
        std::map<char, int> symbol_value;
        char symbol_ori[size] = {M,D,C,L,X,V,I};
        int value_ori[size] = {1000,500,100,50,10,5,1};
        for ( size_t i = 0; i < size; ++i ) 
            symbol_value[symbol_ori[i]]=value_ori[i];

        int result = symbol_value[s[0]];
        for ( size_t i = 1; i < s.size(); ++i )
        {
            if ( symbol_value[s[i]] > symbol_value[s[i-1]] )
            {
                result += symbol_value[s[i]] - 2*symbol_value[s[i-1]];
            }
            else
            {
                result += symbol_value[s[i]];
            }
        }
        return result;
    }
};

tips:

根据Roman数字的构造规则:

如果当前的symbol比前一个symbol大,则当前symbol的值减去二倍之前的那个值,再累加到result中。

(为什么要减2倍,因为这个值之前已经被累加一遍了,所以减去2倍就正好了)

【Roman To Integer】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4494818.html

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