Monday, September 16, 2013

[Leetcode] Integer to Roman

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.



void generateString(char one, char five, char ten,vector& strs)
{
    int i = 1;
    while(i <= 9)
    {
        string str;
        if (i >= 1 && i<= 3)
        {
            str.append(i, one);
        }
        else if (i == 4)
        {
            str.append(1, one);
            str.append(1, five);
        }                
        else if (i == 5)
        {
            str.append(1, five);
        }
        else if (i >= 6 && i <=8)
        {
            str.append(1, five);
            str.append(i-5, one);
        }
        else if (i == 9)
        {
            str.append(1, one);
            str.append(1, ten);
        }
        strs.push_back(str);
        i++;
    }
}

string intToRoman(int num) {
    
    vector n1;
    generateString('I','V','X', n1);

    vector n10;
    generateString('X','L','C', n10);
    
    vector n100;
    generateString('C','D','M', n100);
    
    string ret;
    int d1 = num / 1000;
    if ( d1 > 0)
        ret.append(d1, 'M');
   
    int d2 = (num % 1000)/100;
    if ( d2 > 0)
        ret.append(n100[d2-1]);
        
    int d3 = (num % 100)/10;
    if ( d3 > 0)
        ret.append(n10[d3-1]);
        
    int d4 = num % 10;
    if ( d4 > 0)
        ret.append(n1[d4-1]);
        
    return ret;
}

No comments:

Post a Comment