본문 바로가기
공부/코딩테스트

백준 4988번: Numeral System. Python 파이썬 답안, 백준 코딩테스트 파이썬 풀이

by 혼밥맨 2024. 6. 23.
반응형

백준 4988번: Numeral System. Python 파이썬 답안, 백준 코딩테스트 파이썬 풀이

 

입력

The input is as follows. The first line contains a positive integer n (<= 500) that indicates the number of the following lines. The k+1 th line is the specification of the k th computation (k=1, ..., n).

n 
specification1 
specification2 
...
specificationn 

Each specification is described in a line:

MCXI-string1 MCXI-string2

The two MCXI-strings are separated by a space.

You may assume that the sum of the two MCXI-values of the two MCXI-strings in each specification is less than or equal to 9999.

 

출력

For each specification, your program should print an MCXI-string in a line. Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in the specification. No other characters should appear in the output.

답안

def mcxi_to_int(mcxi):
    value_map = {'m': 1000, 'c': 100, 'x': 10, 'i': 1}
    total = 0
    i = 0
    while i < len(mcxi):
        if mcxi[i].isdigit():
            # Read the digit and the letter
            digit = int(mcxi[i])
            letter = mcxi[i + 1]
            total += digit * value_map[letter]
            i += 2  # Move past the digit and letter
        else:
            # Just a letter
            letter = mcxi[i]
            total += value_map[letter]
            i += 1
    return total

def int_to_mcxi(num):
    parts = [('m', 1000), ('c', 100), ('x', 10), ('i', 1)]
    result = []
    for letter, value in parts:
        count = num // value
        if count == 1:
            result.append(letter)
        elif count > 1:
            result.append(f"{count}{letter}")
        num %= value
    return ''.join(result)

def main():
    import sys
    input = sys.stdin.read
    data = input().splitlines()
    
    n = int(data[0])
    results = []
    
    for i in range(1, n + 1):
        mcxi1, mcxi2 = data[i].split()
        value1 = mcxi_to_int(mcxi1)
        value2 = mcxi_to_int(mcxi2)
        sum_value = value1 + value2
        results.append(int_to_mcxi(sum_value))
    
    for result in results:
        print(result)

if __name__ == "__main__":
    main()
반응형

댓글