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

LeetCode Roman to Integer

时间:2015-01-23 00:54:13      阅读:207      评论: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) {
        if (s.size() == 0) return 0;
        map<char, int> mp;
        mp['I'] = 1;
        mp['V'] = 5; 
        mp['X'] = 10;
        mp['L'] = 50;
        mp['C'] = 100;
        mp['D'] = 500;
        mp['M'] = 1000;

        int len = s.size();
        int sum = mp[s[len-1]];
        for (int i = len-2; i >= 0; i--) {
            if (mp[s[i]] < mp[s[i+1]])
                sum -= mp[s[i]];
            else sum += mp[s[i]];
        }

        return sum;
    }
};
















LeetCode Roman to Integer

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/43035615

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