728x90
반응형
https://www.acmicpc.net/problem/2608
2608번: 로마 숫자
첫째 줄과 둘째 줄에 하나씩 로마 숫자로 표현된 수가 주어진다. 입력된 각 수는 2000 보다 작거나 같고, 두 수의 합은 4000보다 작다.
www.acmicpc.net
풀이
로마숫자 -> 아라비아 숫자
각 로마숫자를 map에 저장한 뒤 로마숫자를 순차적으로 보면서 이전 로마숫자보다 현재 로마숫자가 작다면
현재값 - 이전값 을 해주었습니다.
아라비아숫자 -> 로마숫자
오래고민을 해봤는데 아무리봐도 코드적으로 규칙이 안보여서 하드코딩을 했습니다.
각 자리수에서 [1 ~ 3, 4, 5 ~ 8, 9] 인 경우들로 나누어 생각했습니다.
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <cmath>
using namespace std;
unordered_map<char, int> um;
// 로마숫자를 int 로
int romaToInt(string s) {
int result = 0;
int before = um[s[0]];
for (int i = 1; i < s.length(); i++) {
if (before == 0) {
before = um[s[i]];
continue;
}
// 이전 로마문자가 더 크거나 같은
// 값이라면 그냥 더해준다
if (before >= um[s[i]]) {
result += before;
before = um[s[i]];
}
// 이전 로마숫자가 현재 로마숫자보다 작다면
// 현재값 - 이전값을 해준다.
else {
result += um[s[i]] - before;
before = 0; // 이때 다음 로마숫자는 한칸을 더보고 판단해야함
}
}
return result + before;
}
// 4와 9만 특별취급해주면 되지않을까
string intToRoma(int num) {
string result = "";
for (int i = 3; i >= 0; i--) {
int div = pow(10, i);
int current = num / div;
num %= div;
// 1자리씩 확인
if (current != 0) {
// 1000 자리수일때는 무조건 M을 더해준다.
if (i == 3) {
for (int j = 0; j < current; j++)
result += "M";
}
else if (i == 2) {
if (current == 4)
result += "CD";
else if (current == 9)
result += "CM";
else if (current < 4)
for (int j = 0; j < current; j++)
result += "C";
else {
result += "D";
for (int j = 0; j < current - 5; j++) {
result += "C";
}
}
}
else if (i == 1) {
if (current == 4)
result += "XL";
else if (current == 9)
result += "XC";
else if (current < 4)
for (int j = 0; j < current; j++)
result += "X";
else {
result += "L";
for (int j = 0; j < current - 5; j++) {
result += "X";
}
}
}
else if (i == 0) {
if (current == 4)
result += "IV";
else if (current == 9)
result += "IX";
else if (current < 4)
for (int j = 0; j < current; j++)
result += "I";
else {
result += "V";
for (int j = 0; j < current - 5; j++) {
result += "I";
}
}
}
}
}
return result;
}
void init() {
um['I'] = 1;
um['V'] = 5;
um['X'] = 10;
um['L'] = 50;
um['C'] = 100;
um['D'] = 500;
um['M'] = 1000;
}
int main() {
string s1, s2;
cin >> s1 >> s2;
init();
int ans1 = romaToInt(s1) + romaToInt(s2);
string ans2 = intToRoma(ans1);
cout << ans1 << '\n' << ans2;
}
728x90
반응형