Little Jay

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

알고리즘/BOJ

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

Jay, Lee 2022. 7. 30. 17:15

조금 짜증났던 구현문제

로마 숫자에 익숙하지 않아서 로마 숫자 개념을 이해하고 코드를 구현하는게 조금 어려웠다.

Switch문을 사용할때 break를 안쓰게 되면 다음 Case로 넘어가기 때문에 이를 활용했다. 

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

string a;
int t;

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 >> t;
	while (t--) {
		cin >> a;
		if (a[0] >= '0' && a[0] <= '9') {
			int num = stoi(a);
			cout << numToRoman(num) << endl;
		}
		else 
			cout << romanToNum(a) << endl;
		
	}

	return 0;

}
Comments