Little Jay

[C++] 백준 2608번 - 로마 숫자 본문

알고리즘/BOJ

[C++] 백준 2608번 - 로마 숫자

Jay, Lee 2022. 7. 4. 17:34

naive하게 풀었다.

다른 사람들의 풀이를 보니까 간단한데 구현 문제라 Brute Force처럼 푼 감이 없지 않아 있다. 

이 문제에서 배운거는 switch문에서 local 변수를 선언했을 때 visual studio에서 에러가 난다는 점이다.

이를 위해 여러 블로그를 탐방하였으며, 이유는 switch문은 조건에 따라 로직이 가변적이기 때문에 case 문 내에서 변수를 선언하면 컴파일 시 스택영역의 크기를 정확히 알 수 없기 때문에 case 문을 중괄호로 묶어야 한다는 것이다.

switch를 쓸 때 break를 하지 않고 아래로 내려와야 한다는 것도 주의하면 좋을 것 같다. 

확실히 C++에서 문자열이 나오면 구현의 복잡도와 난이도가 급격하게 상승하는 것 같다. 

 

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

string a, b;

int romanToNum(string &s) {
	int temp = 0;
	int aSize = s.size();
	for (int i = 0; i < aSize; i++) {

		if (s[i] == 'M') {
			temp += 1000;
		}
		else if (s[i] == 'D') {
			temp += 500;
		}
		else if (s[i] == 'C') {
			if (s[i + 1] == 'M') {
				i++;
				temp += 900;
			}
			else if (s[i + 1] == 'D') {
				i++;
				temp += 400;
			}
			else {
				temp += 100;
			}
		}
		else if (s[i] == 'L') {
			temp += 50;
		}
		else if (s[i] == 'X') {
			if (s[i + 1] == 'C') {
				i++; temp += 90;
			}
			else if (s[i + 1] == 'L') {
				i++; temp += 40;
			}
			else {
				temp += 10;
			}
		}
		else if (s[i] == 'V') {
			temp += 5;
		}
		else if (s[i] == 'I') {
			if (s[i + 1] == 'X') {
				i++; temp += 9;
			}
			else if (s[i + 1] == 'V') {
				i++; temp += 4;
			}
			else {
				temp += 1;
			}
		}
	}
	return temp;
}

string numToRoman(int temp) {
	string len = to_string(temp);
	string ans = "";
	switch (len.size())
	{
	case 4: {
		int thousand = temp / 1000;
		while (thousand--) ans += "M";
	}
	case 3: {
		temp %= 1000;
		int hundred = temp / 100;
		if (hundred == 9) {
			ans += "CM";
		}
		else if (hundred == 4) {
			ans += "CD";
		}
		else if (hundred == 5) {
			ans += "D";
		}
		else if (hundred == 1) {
			ans += "C";
		}
		else if (hundred < 4) {
			while (hundred--) ans += "C";
		}
		else if (hundred > 5) {
			ans += "D";
			for (int i = 0; i < hundred - 5; i++) ans += "C";
		}
	}
	case 2: {
		temp %= 100;
		int tenth = temp / 10;
		if (tenth == 9) {
			ans += "XC";
		}
		else if (tenth == 4) {
			ans += "XL";
		}
		else if (tenth == 5) {
			ans += "L";
		}
		else if (tenth == 1) {
			ans += "X";
		}
		else if (tenth < 4) {
			while (tenth--) ans += "X";
		}
		else if (tenth > 5) {
			ans += "L";
			for (int i = 0; i < tenth - 5; i++) ans += "X";
		}
	}
	case 1:
		temp %= 10;
		if (temp == 9) {
			ans += "IX";
		}
		else if (temp == 4) {
			ans += "IV";
		}
		else if (temp == 5) {
			ans += "V";
		}
		else if (temp < 4) {
			while (temp--) ans += "I";
		}
		else if (temp > 5) {
			ans += "V";
			for (int i = 0; i < temp - 5; i++)
				ans += "I";
		}
		break;
	default:
		break;
	}
	return ans;
}

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> a >> b;
	int ans = romanToNum(a) + romanToNum(b);
	cout << ans << endl;
	cout << numToRoman(ans) << endl;

	return 0;
	
}
Comments