CODE-0004 · gemini-3.1-flash-lite (default)
def int_to_roman(n):
    if not 1 <= n <= 3999:
        raise ValueError("Input must be between 1 and 3999.")
    
    val = [
        1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
    ]
    syb = [
        "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
    ]
    roman_num = ''
    i = 0
    while n > 0:
        for _ in range(n // val[i]):
            roman_num += syb[i]
            n -= val[i]
        i += 1
    return roman_num

def roman_to_int(s):
    if not s or not isinstance(s, str):
        raise ValueError("Invalid input.")
    
    mapping = {
        'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
    }
    
    total = 0
    prev_value = 0
    for char in reversed(s):
        if char not in mapping:
            raise ValueError("Invalid character.")
        value = mapping[char]
        if value < prev_value:
            total -= value
        else:
            total += value
        prev_value = value
        
    if int_to_roman(total) != s:
        raise ValueError("Non-canonical or malformed Roman numeral.")
        
    return total