[leetcode] Roman to Integer

来源:互联网 发布:白夜追凶结局知乎 编辑:程序博客网 时间:2024/06/07 03:17

Given a roman numeral, convert it to an integer.

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

思路:

从后往前扫描,当第i个字符比第i+1个字符小时,相减,反之相加

代码:

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



0 0
原创粉丝点击