LeetCode13 - Roman to Integer:罗马数字和阿拉伯数字之间的相互转换

 思路:罗马计数转阿拉伯数字。罗马数字的构造:XCVIII表示98,DCXXI表示621。从右至左,用max记录当前最大数的符号,若当前索引处的数字比max大,则将总数加上当前索引字符所代表的的数,如果小,则将总数减去当前索引所代表的数字。

class Solution {
public:
    int romanToInt(string s) {
        int result=0;
        char Max='I';
        for(int i=s.length()-1;i>=0;i--)
        {
            if(getValue(s[i])>=getValue(Max))
            {
                result+=getValue(s[i]);
                Max=s[i];
            }
            else
            {
                result-=getValue(s[i]);
            }
        }
        return result;
    }
int getValue(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;
    }
    return 0;
}
};
//XCVIII 98
//DCXXI 621

阿拉伯数字转换为罗马计数

思路:罗马数字的基本型为:I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000, 相同的罗马数字最多不能超过3个。所以4只能表示为IV,即5-1,左减右加。同理可得其它基本型,IX = 9, XL = 40, XC = 90, CD = 400, CM = 900。根据这些基本型,我们可以利用贪心策略,每次匹配最大值得到对应的罗马数字表示。

string IntToRoman(int number)
{
    string res = "";
    if (number > 0)
    {
        int num_base[13] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
        string str_base[13] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX","V", "IV", "I" };
        int i = 0;
        while (number != 0) 
        {
            if (number >= num_base[i]) 
            {
                number -= num_base[i];
                res += str_base[i];
            }
            else
                i++;
        }
        return res;
    }
}

 

posted @ 2017-04-09 21:45  蓦然闻声  阅读(307)  评论(0编辑  收藏  举报