Study hard

(c++)백준 1212번: 8진수 2진수 본문

백준/여러가지 문제들

(c++)백준 1212번: 8진수 2진수

Nimgnoej 2020. 6. 17. 19:49

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

 

1212번: 8진수 2진수

첫째 줄에 8진수가 주어진다. 주어지는 수의 길이는 333,334을 넘지 않는다.

www.acmicpc.net

[풀이]

8진수를 2진수로 변환하려면 8진수의 가장 오른쪽 수부터 3자리 2진수로 바꿔주면 된다.

314 = 11001100

수가 0인 경우 바로 0을 출력하도록 하고, 0이 아닌 경우에 1로 시작하도록 2진수를 저장해 둔 스택의 앞부분에 있는 0을 모두 제거한다.

 

#include <iostream>
#include <string>
#include <stack>
using namespace std;

string Octal;
stack<int>Binary;

void solution() {
	cin >> Octal;
	if (Octal == "0") {
		cout << 0 << endl;
		return;
	}

	int Os = Octal.size();
	for (int i = Os - 1; i >= 0; i--) {
		int cur = Octal[i] - '0';
		for (int j = 0; j < 3; j++) {
			int num = cur % 2;
			cur = cur / 2;
			Binary.push(num);
		}
	}
	//반드시 1로 시작해야 하므로 가장 먼저 오는 1을 찾음
	while (Binary.top() != 1) {
		Binary.pop();
	}
	while (!Binary.empty()) {
		cout << Binary.top();
		Binary.pop();
	}
	cout << endl;
}

int main() {
	solution();
	return 0;
}