My C++ solution


  • 0
    T
    class Solution {
    public:
        int romanToInt(string s) {
            int val = 0;
            char prev = ' ';
            for(string::iterator it = s.begin(); it != s.end(); ++it) {
                char c = *it;
                switch (c) {
                case 'I':
                    val += 1;
                    break;
                case 'V':
                    val += 5;
                    if(prev == 'I') {
                        val -= 2;
                    }
                    break;
                case 'X':
                    val += 10;
                    if(prev == 'I') {
                        val -= 2;
                    }
                    break;
                case 'L':
                    val += 50;
                    if(prev == 'X') {
                        val -= 20;
                    }
                    break;
                case 'C':
                    val += 100;
                    if(prev == 'X') {
                        val -= 20;
                    }
                    break;
                case 'D':
                    val += 500;
                    if(prev == 'C') {
                        val -= 200;
                    }
                    break;
                case 'M':
                    val += 1000;
                    if(prev == 'C') {
                        val -= 200;
                    }
                    break;
                }
                prev = c;
            }
            return val;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.