LeetCode 013 Roman to Integer

来源:互联网 发布:华为网络竞赛上机题 编辑:程序博客网 时间:2024/05/17 02:08

【题目】


Given a roman numeral, convert it to an integer.

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


【题意】

把罗马数转换为整数


【思路】

罗马数字中只使用如下七个基值字母:M,D,C,L,X,V,I,分别用来表示1000、500、100、50、10、5、1。
大体思路是每个罗马字母对应的值相加即可,
但需要处理900, 400, 90, 40, 9, 4这几个特殊值(左边的罗马字符比右边的小)


【代码】

class Solution {public:    int romanToInt(string s) {        int result=0;        int size=s.length();        if(size==0)return 0;        map<char, int> rom2int={{'M',1000},{'D',500},{'C',100},{'L',50},{'X',10},{'V',5},{'I',1}};        for(int i=0; i<size; i++){            if(i!=size-1 && rom2int[s[i]]<rom2int[s[i+1]]){                result+=(rom2int[s[i+1]]-rom2int[s[i]]);                i++;            }            else result+=rom2int[s[i]];        }        return result;    }};


0 0
原创粉丝点击