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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容