티스토리 뷰

728x90

https://www.acmicpc.net/problem/2608

 

2608번: 로마 숫자

첫째 줄과 둘째 줄에 하나씩 로마 숫자로 표현된 수가 주어진다. 입력된 각 수는 2000 보다 작거나 같고, 두 수의 합은 4000보다 작다.

www.acmicpc.net

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
nums = {'I'1'V'5'X'10'L'50'C'100'D'500'M'1000}
extra = {'IV'4'IX'9'XL'40'XC'90'CD'400'CM'900}
 
 
def to_num(S):
    chk = [0* len(S)
    tot = 0
    for i in range(len(S)):
        if not chk[i]:
            if i+1 < len(S) and S[i:i+2in extra:
                tmp = S[i:i+2]
                tot += extra[tmp]
                chk[i:i+1= 11
            else:
                tot += nums[S[i]]
                chk[i] = 1
    return tot
 
 
def to_str(N):
    ans, cnt = ''0
    t, n = len(N), len(N)
    while n:
        num = int(N[t-n])
        if n == 4:
            ans += 'M'*num
        elif n == 3:
            if num == 9:
                ans += 'CM'
            elif num == 4:
                ans += 'CD'
            else:
                if num >= 5:
                    ans += 'D'
                ans += 'C'*(num % 5)
        elif n == 2:
            if num == 9:
                ans += 'XC'
            elif num == 4:
                ans += 'XL'
            else:
                if num >= 5:
                    ans += 'L'
                ans += 'X'*(num % 5)
        elif n == 1:
            if num == 9:
                ans += 'IX'
            elif num == 4:
                ans += 'IV'
            else:
                if num >= 5:
                    ans += 'V'
                ans += 'I'*(num % 5)
        n -= 1
    return ans
 
 
A, B = input(), input()
= to_num(A)
= to_num(B)
total = a + b
print(total)
print(to_str(str(total)))
cs

 

댓글