13. Roman to Integer

1.问题描述

Given a roman numeral, convert it to an integer.

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

2.分析

3.代码

int map(const 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;
        default: return 0;
    }
}

int romanToInt(char* s) {
    unsigned int length = strlen(s);
    int sum = 0;
    for (unsigned int i = 0; i < length; ++i) {
        if (i == length-1) {
            sum += map(s[i]);
            break;
        }
        if (map(s[i]) >= map(s[i+1])) sum += map(s[i]);
        if (map(s[i]) < map(s[i+1])) {
            sum += -map(s[i]) +map(s[i+1]);
            i++;
        }
    }
    return sum;
}

你可能感兴趣的:(13. Roman to Integer)