728x90
728x90

문제 링크 : https://www.acmicpc.net/problem/1373

 

1373번: 2진수 8진수

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

www.acmicpc.net

 

 

문제

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

입력

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

출력

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

 

 


접근 방법

세자리씩 끊어서 8진수로 변환해야 하므로, 길이를 3의 배수로 맞춰준다.

 

str = "011001100"을 세자리씩 끊어서 생각해보자.

011 = 0*4 + 1*2 + 1*1 = 3

001 = 0*4 + 0*2 + 1*1 = 1

100 = 1*4 + 0*2 + 0*1 = 4

인 것을 확인할 수 있다. 

 

(16진수는 4자리씩 끊어서 생각하면 된다.)

 

//
//  문자열_BOJ1373_2진수8진수.cpp
//  Coding_Test_Practice
//
//  Created by 김난영 on 2021/07/07.
//  Copyright © 2021 KimNanyoung. All rights reserved.
//

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

int main(){ cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false);
    
    string str; cin >> str;
    while(str.length() % 3 != 0){
        str = '0' + str;
    }

    for(int i = 0; i<str.length(); i+=3){   //i = 0, 3, 6, ,,
        int num = (str[i]-'0')* 4 + (str[i+1]-'0')* 2 + (str[i+2] - '0')* 1;
        cout << num;
    }
       
    return 0;
}

728x90

+ Recent posts