sundeepblue
3/10/2014 - 1:51 AM

Given a roman numeral, convert it to an integer, or vice versa.

Given a roman numeral, convert it to an integer, or vice versa.

// suppose 1 <= 'num' <= 3999
string integer_to_roman(int num) {
    int base[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
    // I, V, X, L, C, D, M
    // 1, 5, 10,50,100,500,1000
    string symb[] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
    string res = "";
    for(int i=12; i>=0; i--) {
        while(num >= base[i]) {
            num -= base[i]; // gist, continuously substract
            res += symb[i];
        }
    }
    return res;
}

int roman_to_integer(string s) {
    int res = 0;
    for(int i=0; i<s.size(); i++) {
        if(i == 0) res += convert(s[i]);
        else {
            int cur = convert(s[i]), pre = convert(s[i-1]);
            if(pre < cur) res += cur - pre - pre; // gist, substract twice the pre
            else res += cur;
        }
    }
    return res;
}

int convert(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 0;
    }
}