【leetcode】7 Roman to Integer

罗马字符转整数

注意事项:

1 几个罗马字符对应的整数

 'I':  1;
 'V':  5;
 'X':  10;
 'L':   50;
 'C':  100;
 'D':  500;
 'M': 1000;

2 对于DC这种前者大于后者的好处理,

对于CD这种前者小于后者的,相当于C+D-2*C

class Solution {
public:
    int toInt(char x){
        switch(x){
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
        }
       
    }
    int romanToInt(string s) {
         int rest=toInt(s[0]);
         for(int i=1;i<s.length();i++){
             if(toInt(s[i-1])<toInt(s[i])){
                 rest+=toInt(s[i])-2*toInt(s[i-1]);
             }else
                 rest+=toInt(s[i]);
         }
         return rest;
       
    }
};

原文地址:https://www.cnblogs.com/wygyxrssxz/p/4493791.html