[C++] 백준 16506번: CPU

be_clever·2022년 2월 24일
0

Baekjoon Online Judge

목록 보기
91/172

문제 링크

16506번: CPU

문제 요약

주어진 어셈블리어 코드를 표를 참조해 기계어 코드로 바꿔야 한다.

접근 방법

단순 구현 문제입니다. 문자열 처리와 10진수를 2진수로 변환하는 것에만 주의를 하면 되는 간단한 구현 문제였습니다.

코드

#include <bits/stdc++.h>

using namespace std;

string arr[12] = { "ADD", "SUB", "MOV", "AND", "OR", "NOT", "MULT", "LSFTL", "LSFTR", "ASFTR", "RL", "RR" };

string to_binary_number(int num, int len)
{
	vector<char> tmp;
	string ret;

	while (num)
	{
		tmp.push_back('0' + num % 2);
		num /= 2;
	}

	reverse(tmp.begin(), tmp.end());

	for (int i = 0; i < len - tmp.size(); i++)
		ret.push_back('0');

	for (auto& i : tmp)
		ret.push_back(i);
        
	return ret; 
}

int main(void)
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n;
	cin >> n;

	while (n--)
	{
		int num1, num2, num3;
		string opcode, ans;
		cin >> opcode >> num1 >> num2 >> num3;

		bool flag = false;
		if (opcode[opcode.size() - 1] == 'C')
		{
			opcode.pop_back();
			flag = true;
		}

		for (int i = 0; i < 12; i++)
		{
			if (arr[i] == opcode)
			{
				ans += to_binary_number(i, 4);
				break;
			}
		}

		ans.push_back((flag ? '1' : '0'));
		ans.push_back('0');
		ans += to_binary_number(num1, 3);
		ans += to_binary_number(num2, 3);

		if(flag)
			ans += to_binary_number(num3, 4);
		else
		{
			ans += to_binary_number(num3, 3);
			ans.push_back('0');
		}

		cout << ans << '\n';
	}

	return 0;
}
profile
똑똑해지고 싶어요

0개의 댓글