C solution to Roman2Int problem


  • 0
    D

    It is obvious that Roman numerals consist of 'I', 'V', 'X', 'L', 'C', 'D', 'M', representing for 1, 5, 10, 50, 100, 500, 1000. We also know that a number reside to the left of a larger number means subtraction operation. Symmetrically, a number reside to the right of an equal or larger number means addition operation. With that in mind, let's look at 2 examples:

    1. IV
      The answer is 4, because 'I' is smaller than as well as left to 'V', so we interpret it as: 'V' - 'I' = 4.
    2. LXV
      The answer is 65, because 'X' is larger than and right to 'V', so we add them: 'X' + 'V' = 15; meanwhile, 'L' and 'X' show us the same pattern, we we do addition again: 'L' + previous result = 65.

    Now we have no trouble interpreting Roman numerals. In my solution, I firstly define a function for the convenience of transferring a Roman char to an int type, then apply algorithm on it:

    int charToInt( 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 -1;
        }
    }
    
    int romanToInt(char* s) {
        char prev, curr;
        int sum, len, a, b;
        len = strlen( s );
        prev = s[len - 1];
        sum = charToInt( prev );
        
        while( --len > 0 ) {
            curr = s[len - 1];
            a = charToInt( prev );
            b = charToInt( curr ) ;
            prev = curr;
            sum = a > b ? sum - b : sum + b;
        }
        
        return sum;
    }
    

    However, my solution does not check error for illegal inputs that violate the rules of representing Roman numerals. Solution rests on the surmise of correct input.


Log in to reply
 

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