본문 바로가기
Algorithm/BackJoon

1373번: 2진수 8진수

by 꼬부기가우는소리 2023. 9. 5.
728x90

 

- 문제 사이트: https://www.acmicpc.net/problem/1373

 

1373번: 2진수 8진수

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

www.acmicpc.net

 

입력 받은 2진수를 8진수로 변환해주는 문제이다.

끝 문자부터 3자리씩 잘라서 8진수로 변환해주었다.

 

1) 끝에서 앞으로 세번째 index 확인: start → 해당 값이 마이너스일 경우, 0으로 변환

2) 1) 기준 세 문자로 자를 시, 마지막 index 확인 = start + 2 = end

3) start 부터 end 까지 문자열 잘라내기

4) 잘라낸 문자열을 8진수로 변환: binToOct(string str)

5) 변환된 8진수 값을 string으로 저장해준 뒤, 모든 변환 완료되면 출력

예시 2진수 start와 end 값 잘라낸 문자열 8진수로 변환 모두 변환 완료 역순으로 출력 (결과)
1 110 start = 0 && end = 2 110 4 + 2 + 0 = 6 6 (110) 6
2 10100 start = 2 && end = 4 100 4 + 0 + 0 = 4 42 (100 / 10) 24
3 11 start = -1 && end = 1
→ start = 0 && end = 1
11 2 + 1 = 3 3 (11) 3
4 11001100 start = 5 && end = 7 100 4 + 0 + 0 = 4 413 (100 / 001 / 11) 314

 

#include <iostream>
#include <cmath>
using namespace std;

string binToOct(string bin)
{
    int oct = 0;
    for (int i = bin.length() - 1; i >= 0; i--)
    {
        oct += (bin[i] - '0') * pow(2, bin.length() - 1 - i);
    }
    return to_string(oct);
}

int main()
{
    string bin;
    cin >> bin;

    string oct = "";
    int start = bin.length() - 3;
    int end = start + 2;
    int length;
    while (end >= 0)
    {
        if (start < 0)
            start = 0;

        length = end - start + 1;
        oct += binToOct(bin.substr(start, length));

        end = start - 1;
        start -= 3;
    }

    for (int i = oct.length() - 1; i >= 0; i--)
        cout << oct[i];
    return 0;
}

- 메모리: 5104 KB

- 시간: 68 ms

- 코드 길이: 700 B

* 연관 문제:

- [백준] 1212번: 8진수 2진수

'Algorithm > BackJoon' 카테고리의 다른 글

5543번: 상근날드  (0) 2023.09.07
2559번: 수열  (0) 2023.09.06
10820번: 문자열 분석  (0) 2023.09.04
12789번: 도키도키 간식드리미  (0) 2023.09.03
11659번: 구간 합 구하기 4  (0) 2023.09.01

댓글