LeetCode Roman to Integer

来源:互联网 发布:全知视角举例 编辑:程序博客网 时间:2024/06/05 06:14
class Solution {public:    int hash[256];    Solution(){        memset(hash, 0, sizeof(hash));        hash['I']=1;        hash['V']=5;        hash['X']=10;        hash['L']=50;        hash['C']=100;        hash['D']=500;        hash['M']=1000;    }    int romanToInt(string s) {        int ans=0;        for (int i=0; i<s.size();i++) {            switch (s[i]) {                case 'I':                {                    if (i+1<s.size()&&(s[i+1]=='V'||s[i+1]=='X')) {                        ans+=hash[s[i+1]]-hash[s[i]];                        i++;                    }                    else{                        ans+=hash[s[i]];                    }                    break;                }                case 'X':{                    if (i+1<s.size()&&(s[i+1]=='L'||s[i+1]=='C')) {                        ans+=hash[s[i+1]]-hash[s[i]];                        i++;                    }else{                        ans+=hash[s[i]];                    }                    break;                }                case 'C':{                    if (i+1<s.size()&&(s[i+1]=='D'||s[i+1]=='M')) {                        ans+=hash[s[i+1]]-hash[s[i]];                        i++;                    }else{                        ans+=hash[s[i]];                    }                    break;                }                default:{                    ans+=hash[s[i]];                    break;                }                               }                    }        return ans;    }};

0 0