a easy and fast function for roman to integer with C language


  • 0
    R

    typedef struct{
    int value;
    int num_bi;
    }num_obj;

    num_obj roman[32];

    int romanToInt(char* s) {

    int num = 0;
    int index = 0;
    char *pC = s;
    
    roman[8].value = 1;// I	
    roman[21].value = 5;// V	
    roman[23].value = 10;// X	
    roman[11].value = 50;// L	
    roman[2].value = 100;// C	
    roman[3].value = 500;// D	
    roman[12].value = 1000;// M
    
    roman[8].num_bi = 1;// I	
    roman[21].num_bi = 2;// V	
    roman[23].num_bi = 3;// X	
    roman[11].num_bi = 4;// L	
    roman[2].num_bi = 5;// C	
    roman[3].num_bi = 6;// D	
    roman[12].num_bi = 7;// M
    
    while(pC[index]!= '\0')
    {
        if(index>=1)
        {
            if(roman[pC[index]-'A'].num_bi<=roman[pC[index-1]-'A'].num_bi )
    		{
    			if(pC[index+1] == '\0')
    			{
    				num += roman[pC[index]-'A'].value;
    				break;
    			}
    			else
    			{
    				 if( roman[pC[index+1]-'A'].num_bi<roman[pC[index-1]-'A'].num_bi)
    				 {
    					num += roman[pC[index]-'A'].value;
    					index++;
    				 }
    				 else if( roman[pC[index+1]-'A'].num_bi == roman[pC[index-1]-'A'].num_bi)
    				 {
    					 if(roman[pC[index+1]-'A'].num_bi == roman[pC[index]-'A'].num_bi)
    					 {
    					num += roman[pC[index+1]-'A'].value + roman[pC[index]-'A'].value;
    					 }
    					 else
    					 {
    					 num += roman[pC[index+1]-'A'].value - roman[pC[index]-'A'].value;
    					 }
    					index++;
    					index++;
    					pC += index;
    					index =0;
    				 }
    				 else
    				 {
    					num += (roman[pC[index+1]-'A'].value-roman[pC[index]-'A'].value);
    					index++;
    					index++;
    					pC += index;
    					index = 0;
    				 }
    			}
                 
            }
            else
            {
                 num += roman[pC[index]-'A'].value;
                 num -= 2*roman[pC[index-1]-'A'].value;
    			 index++;
            }
        }
        else
        {
            num += roman[pC[index]-'A'].value;
    		index++;
        }
        
        
    }
    return num;
    

    }


Log in to reply
 

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