Hackbright Code Challenges

Roman Numerals: Solution

Roman Numerals: Solution

Problem

Roman Numerals

Whiteboard

Harder

Challenge

Medium

Concepts

General, Math

Download

roman-numerals-solution.zip


def to_roman(num):
    """Converts positive integers to Roman numeral equivalent using Old-school style."""

    if num != int(num) or num > 4999 or num < 1:
        raise ValueError("Cannot convert")

    # START SOLUTION

    roman = ''
    num_string = str(num)

    if len(num_string) == 4:
        roman += ROMAN_DIGIT[1000] * int(num_string[0])
        num_string = num_string[1:]

    if len(num_string) == 3:
        curr_digit = int(num_string[0])
        if curr_digit >= 5:
            roman += ROMAN_DIGIT[500]
            curr_digit -= 5
        roman += ROMAN_DIGIT[100] * curr_digit
        num_string = num_string[1:]

    if len(num_string) == 2:
        curr_digit = int(num_string[0])
        if curr_digit >= 5:
            roman += ROMAN_DIGIT[50]
            curr_digit -= 5
        roman += ROMAN_DIGIT[10] * curr_digit
        num_string = num_string[1:]

    if len(num_string) == 1:
        curr_digit = int(num_string[0])
        if curr_digit >= 5:
            roman += ROMAN_DIGIT[5]
            curr_digit -= 5
        roman += ROMAN_DIGIT[1] * curr_digit

    return roman