A simple solution written in C.


  • 0
    J
    int romanToInt(char* s) {
        int *arr;
        int len;
        int index;
        int _last;
        int sum;
        
        len   = strlen((const char*)s);
        arr   = (int *)malloc(len * sizeof(int));
        if (NULL == arr)
            exit(1);
    
        memset(arr, 0, len);
        _last = 0;
        
        for (index = 0; index < len; ++index)
        {
            char c = s[index];
            int i  = 0;
        
            switch(c) {
            case 'M':
                i = 1000;
                break;
    
            case 'D':
                i = 500;
                break;
            
            case 'C':
                i = 100;
                break;
                    
            case 'L':
                i = 50;
                break;
    
            case 'X':
                i = 10;
                break;
                    
            case 'V':
                i = 5;
                break;
            
            case 'I':
                i = 1;
                break;
                    
            default:
                i = 0;
                break;
            }
    
            arr[index] = i;
            if (0 == index || i <= _last)
            {
                _last = i;
                continue;
            }
            
            /* If i < last */
            int _rev;
            for (_rev = (index - 1); _rev >= 0; --_rev)
            {
                int _r = arr[_rev];
                if (_r >= i)
                    break;
                
                arr[_rev] = arr[_rev] * (-1);
            }
            _last = i;
        }
        
        /* Join sum */
        sum = 0;
        for(index = 0; index < len; ++index)
        {     
            sum += arr[index];
        }
        
        return sum;
    }
    

Log in to reply
 

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