美文网首页
13. Roman to Integer

13. Roman to Integer

作者: YellowLayne | 来源:发表于2017-06-14 10:11 被阅读0次

    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

          本文链接:https://www.haomeiwen.com/subject/efrsqxtx.html