Monday, April 7, 2014

LeetCode: Integer to Roman

Given an integer, convert it to a roman numeral.

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


The solution is trivial. Just using greedy method.

C++ Code:

/*
 * func: int_to_roman
 * goal: change an integer to a roman numeral
 * @param num: the input integer
 * return: roman numeral string
 */
/*
 * use greedy method
 */
string int_to_roman(int num){
    if(num < 1 || num > 3999){
        throw std::invalid_argument("input number is out of range");
        return "";
    }
    string ret = "";
    while(num > 0){
        if(num >= 1000){
            ret += "M";
            num -= 1000;
        }else if(num >= 900){
            ret += "CM";
            num -= 900;
        }else if(num >= 500){
            ret += "D";
            num -= 500;
        }else if(num >= 400){
            ret += "CD";
            num -= 400;
        }else if(num >= 100){
            ret += "C";
            num -= 100;
        }else if(num >= 90){
            ret += "XC";
            num -= 90;
        }else if(num >= 50){
            ret += "L";
            num -= 50;
        }else if(num >= 40){
            ret += "XL";
            num -= 40;
        }else if(num >= 10){
            ret += "X";
            num -= 10;
        }else if(num >= 9){
            ret += "IX";
            num -= 9;
        }else if(num >= 5){
            ret += "V";
            num -= 5;
        }else if(num >= 4){
            ret += "IV";
            num -= 4;
        }else if(num >= 1){
            ret += "I";
            num -= 1;
        }
    }
    
    return ret;
}

Python Code:

# func: convert the integer to roman numeral
# @param: input integer num
# @return: a roman numeral string
def int_ro_roman(num):
    assert 1 <= num <= 3999

    ret = ""
    while num > 0:
        if num >= 1000:
            ret += "M"
            num -= 1000
        elif num >= 900:
            ret += "CM"
            num -= 900
        elif num >= 500:
            ret += "D"
            num -= 500
        elif num >= 400:
            ret += "CD"
            num -= 400
        elif num >= 100:
            ret += "C"
            num -= 100
        elif num >= 90:
            ret += "XC"
            num -= 90
        elif num >= 50:
            ret += "L"
            num -= 50
        elif num >= 40:
            ret += "XL"
            num -= 40
        elif num >= 10:
            ret += "X"
            num -= 10
        elif num >= 9:
            ret += "IX"
            num -= 9
        elif num >= 5:
            ret += "V"
            num -= 5
        elif num >= 4:
            ret += "IV"
            num -= 4
        elif num >= 1:
            ret += "I"
            num -= 1
    return ret

Reference Link:

Roman numerals: http://en.wikipedia.org/wiki/Roman_numerals

No comments:

Post a Comment