C++ solution


  • 0
    R
    class Solution {
    public:
        int romanToInt(string s) {
            int res = 0;
            string rom[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
            int num[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
            
            for(int i = 0; i < 13; i++) {
                if(s.size() > 0) {
                    while(rom[i] == s.substr(0, 1) || rom[i] == s.substr(0, 2)) {
                        res += num[i];
                        if(rom[i] == s.substr(0, 1))
                            s = s.substr(1);
                        else
                            s = s.substr(2);
                    }
                    
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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