13. Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

int toNumber(char ch) {
    switch (ch) {
        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;
    }
    return 0;
}

int romanToInt(char* s) {
    int len = strlen(s);
    int ret = 0;
    
    for(int i = 0; i < len; i++){
        if(i+1 < len && toNumber(s[i+1]) > toNumber(s[i])){
            ret += toNumber(s[i+1]) - toNumber(s[i]);
            i++;
        }
        else ret += toNumber(s[i]);
    }
    return ret;
}

 

posted on 2016-04-13 18:54  joannae  阅读(154)  评论(0编辑  收藏  举报

导航