algorithm/BOJ

BOJ 1373번 2진수 8진수

_JunHo 2020. 1. 13. 14:40

BOJ : https://www.acmicpc.net/problem/1373

 

1373번: 2진수 8진수

첫째 줄에 2진수가 주어진다. 주어지는 수의 길이는 1,000,000을 넘지 않는다.

www.acmicpc.net

 

2진수를 8진수로 변환하는 문제

8진수가 0~7의 범위를 표현할 수 있다는 점을 이용하면

0~7 은 2진수로 3자리 000~111 로 표현할 수 있다.

그러므로 2진수를 3자리씩 끊어서 확인하면 해결할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <stack>
using namespace std;
 
stack<int> s;
 
int main() {
    ios::sync_with_stdio(0);
    int cnt = 0, total = 0;
    bool check = true;
    string str;
    cin >> str;
    for (int i = str.size() - 1; i >= 0; i--) {
        if (cnt == 3) {
            check = false;
            s.push(total);
            cnt = 0;
            total = 0;
        }
        if (str[i] == '1') {
            check = true;
            int temp = 1;
            for (int k = 0; k < cnt; k++) {
                temp *= 2;
            }
            total += temp;
        }
        cnt++;
    }
    if (check) s.push(total);
    while (!s.empty()) {
        cout << s.top(), s.pop();
    }
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter