O(n) c++ solution share


  • 5
    H
        class Solution {
    public:
        int romanToInt(string s) {
        int RTI[s.size()+1]={0};
    	int max,i;
            max=0;
    	for(i=0;i<s.size();i++)
    	{
    	  switch(s[i])
    	  {
    	  case 'I':RTI[i]=1;break;
    	  case 'V':RTI[i]=5;break;
    	  case 'X':RTI[i]=10;break;
    	  case 'L':RTI[i]=50;break;
    	  case 'C':RTI[i]=100;break;
    	  case 'D':RTI[i]=500;break;
    	  case 'M':RTI[i]=1000;break;
    	  }
    	}
        for(i=0;i<s.size();i++)
    		max+=(RTI[i]>=RTI[i+1])?RTI[i]:(-1*RTI[i]);
    	return max;
        }
    };

  • 0
    D

    Cool. Well done. This is working perfectly.


Log in to reply
 

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