leetcode ---13 罗马数字转整数

首先建map映射关系,将阿拉伯数与罗马数字一一对应。然后建立两个值,一个用来得到现在遍历的值,另一个用于保存上一个值,从整个数组最后一位开始向前遍历,当当前数字比上一个数大时,直接加上,当当前值比上一个小时,直接减去。最后遍历结束返回、

  int romanToInt(string s) {
        int sum=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 temp=0;
        int temp1=0;
        for(int i=s.length()-1;i>=0;i--)
        {
            temp=m[s[i]];
            if(temp>=temp1)
            {
                sum+=temp;
                temp1=temp;
            }
            else
            {
                sum-=temp;
                temp1=temp;
            }
        }
        return sum;
    }

猜你喜欢

转载自www.cnblogs.com/biubiuWham/p/10287062.html