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

Roman to Integer leetcode

时间:2016-01-05 22:14:45      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

Given a roman numeral, convert it to an integer.

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

 

Subscribe to see which companies asked this question

Ⅰ(1)Ⅴ(5)Ⅹ(10)L(50)C(100)D(500)M(1000)

规则:位于大数的后面时就作为加数;位于大数的前面就作为减数

如:Ⅲ=3,Ⅳ=4,Ⅵ=6,ⅩⅨ=19,ⅩⅩ=20,ⅩLⅤ=45,MCMⅩⅩC=1980

从最低位开始,如果前面的数比它大,则让前面的数值加后面的数值,如果比它小,则让当前数值减去前面的数值

int romanToInt(string s) {
    if (s.length() == 0) return 0;
    int len = s.length();
    unordered_map<char, int> map;
    map.insert(make_pair(I, 1));
    map.insert(make_pair(V, 5));
    map.insert(make_pair(X, 10));
    map.insert(make_pair(L, 50));
    map.insert(make_pair(C, 100));
    map.insert(make_pair(D, 500));
    map.insert(make_pair(M, 1000));
    int result = map.at(s.at(len - 1));
    int pivot = result;
    for (int i = len - 2; i >= 0; i--) {
        int curr = map.at(s.at(i));
        if (curr >= pivot) {
            result += curr;
        }
        else {
            result -= curr;
        }
        pivot = curr;
    }
    return result;
}

 

Roman to Integer leetcode

标签:

原文地址:http://www.cnblogs.com/sdlwlxf/p/5103763.html

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