본문 바로가기

Algorithm/Math

[C++] 백준 1373번 : 2진수 8진수 (B2)

#문제

www.acmicpc.net/problem/1373

 

1373번: 2진수 8진수

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

www.acmicpc.net

#풀이 & 학습한 내용

먼저 2진수인 수의 총 길이가 3의배수가 되지 않을때, 총 길이가 3의 배수가 되도록 앞에 0을 추가해준다. 그리고 3개씩 잘라서 2진수의 값을 10진수로 변환하여 순서대로 출력하면, 8진수로 변환된 결과가 나온다.

이때, char로 표현된 0~9를 int로 다루고 싶으면 '0'을 빼주면 된다는 점을 기억하자.

 

#소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<algorithm>
#include<string>
 
using namespace std;
 
int main(void) {
    string str;
    cin >> str;
    
    while (str.length() % 3 != 0)
        str = "0" + str;
    
    for (int i = 0; i < str.length(); i += 3) {
        cout << 4 * (str[i] - '0'+ 2 * (str[i + 1- '0'+ 1 * (str[i + 2- '0');
    }
}
cs

 

github.com/HoYoungChun/BOJ_algorithm/blob/master/Math/BOJ_1373.cpp

 

HoYoungChun/BOJ_algorithm

Baekjoon Online Judge problem solving by C++. Contribute to HoYoungChun/BOJ_algorithm development by creating an account on GitHub.

github.com