C++ Solution (24ms beats 100%)


  • 3
        int romanToInt(string s) {
            int dic[26];
            dic['I'-'A']=1;
            dic['V'-'A']=5;
            dic['X'-'A']=10;
            dic['L'-'A']=50;
            dic['C'-'A']=100;
            dic['D'-'A']=500;
            dic['M'-'A']=1000;
    
            int intValue = 0; 
            int prev = 0; 
            for(int i = s.size() - 1; i >= 0; i--) {
                int addOrSubtract = dic[s[i] - 'A']; 
                intValue += (prev > addOrSubtract) ? -addOrSubtract : addOrSubtract; 
                prev = addOrSubtract; 
            }
            return intValue; 
    
        }
    

    Similar idea to most other solutions, but I held onto a previous variable to determine if i want to add or subtract for each character we see in the Roman Numeral.


  • 0
    L

    after submitting the following codes first time, which beats 100% !!.
    unfortrunately, when I changed a little bit and submitted it, which only beats 53.%.

    int romanToInt(string s) {
    int dict[26];
    dict['M'-'A'] = 1000;
    dict['D'-'A'] = 500;
    dict['C'-'A'] = 100;
    dict['L'-'A'] = 50;
    dict['X'-'A'] = 10;
    dict['V'-'A'] = 5;
    dict['I'-'A'] = 1;

    	int res(0), pre(0), curr;
    	for ( int i(0); i<s.size(); ++i )
    	{
    		curr = dict[s.at(i)-'A'];
    		res += (pre<curr) ? (curr - pre*2) : curr;
    		pre = curr;
    	}
    
    	return res;
    

    }


Log in to reply
 

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