My easy-to-understand C++ solutions


  • 25
    X
       class Solution {
        public:
            int romanToInt(string s) {
                int num = 0;
                int size = s.size();
                
                for (int i = 0; i < size; i++) {
                	if (i < (size - 1) && romanCharToInt(s[i]) < romanCharToInt(s[i + 1])) {
                		num -= romanCharToInt(s[i]);
                	} else {
        				num += romanCharToInt(s[i]);
        			}
                }
                return num;
            }
            
            int romanCharToInt(char c) {
            	switch (c) {
            		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;
            		default:	return 0;
            	}
            }
        };
    

    The code is faster if the body of the for loop is replaced with:

    	if (i < (size - 1) && (
    		'I' == s[i] && ('V' == s[i + 1] || 'X' == s[i + 1]) ||
    		'X' == s[i] && ('L' == s[i + 1] || 'C' == s[i + 1]) ||
    		'C' == s[i] && ('D' == s[i + 1] || 'M' == s[i + 1]) )) {
    		num -= romanCharToInt(s[i]);
    	} else {
    		num += romanCharToInt(s[i]);
    	}
    

  • 1
    S

    Same idea. Here is my Java version

    public class Solution {
        public int romanToInt(String s) {
            int result = 0;
            
            for (int i = 0; i < s.length() - 1; i++)
            {
                if (getValue(s.charAt(i)) < getValue(s.charAt(i+1)))
                    result -= getValue(s.charAt(i));
                else
                    result += getValue(s.charAt(i));
            }
            return result + getValue(s.charAt(s.length()-1));
        }
        
        public int getValue(char c)
        {
            if (c == 'I')
                return 1;
            else if (c == 'V')
                return 5;
            else if (c == 'X')
                return 10;
            else if (c == 'L')
                return 50;
            else if (c == 'C')
                return 100;
            else if (c == 'D')
                return 500;
            else
                return 1000;
        }
    }

  • 0
    H

    quite straightforward!


Log in to reply
 

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