-- 예전 기록/BOJ

[ BOJ ] 1373 : 2진수 8진수 ( BRONZE 1 ) / C, Python

rejo 2023. 11. 21. 10:50

문제

2진수가 주어졌을 때, 8진수로 변환하는 프로그램을 작성하시오.

입력

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

출력

첫째 줄에 주어진 수를 8진수로 변환하여 출력한다.

풀이 과정

2진수의 길이가 길기 때문에 10진수로 변환하기엔 무리가 있고, 8진수로 다이렉트로 변환해야 한다.

2진수를 오른쪽부터 3자리씩 끊어서 8진수로 바로 변환한다.

C

#include <stdio.h>
#include <string.h>

char n[1000005];
int result[1000005];
int result_size = 0;

int max(int a, int b) {
    if (a > b) return a;
    return b;
}

int main(void) {
    scanf("%s", n);
    int n_size = strlen(n);

    for (int i = n_size - 1; i >= 0; i -= 3) {
        int c = 0;
        int now = 0;
        for (int k = i; k > max(i - 3, -1); k--) {
            now += (n[k] - '0') << c;
            c += 1;
        }
        result[result_size++] = now;
    }

    for (int i = result_size - 1; i >= 0; i--)
        printf("%d", result[i]);
    return 0;
}

Python

import sys
input = sys.stdin.readline

string = input().rstrip()
print(oct(int(string, 2))[2:])