BOJ 2998번 8진수 문제

2진수를 8진수로 고치는 문제다.

2진수 글자 수가 3의 배수가 아니면 앞에 0을 붙인다.

3글자씩 봐서 000일 경우 0, 001일 경우 1, 010일 경우 2 ... 를 결과 string에 넣고 출력하는 간단한 문제였다.

한번 제출에서 틀렸는데, 111 같이 처음부터 길이가 3의 배수일때 07로 출력을 하는 경우 때문이였다.

그래서 if문으로 3의 배수가 아닐때만 앞에 0을 붙이게 하고 제출했다.

2998.cpp

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

char check(char, char, char);

int main() {
    string si;
    cin >> si;
    int stringSize = si.size();
    if (stringSize % 3 != 0) {
        int threeRemainder = stringSize % 3;
        int plus = 3 - threeRemainder;
        for (int i = 0; i < plus; i++) {
            si = "0" + si;
        }
    }
    int howmany = si.size() / 3;
    string result;
    for (int i = 0; i < howmany; i++) {
        result[i] = check(si[3 * i], si[3 * i + 1], si[3 * i + 2]);
        cout << check(si[3 * i], si[3 * i + 1], si[3 * i + 2]);
    }
}

char check(char one, char two, char three) {
    if (one == '0' && two == '0' && three == '0') {
        return '0';
    }
    if (one == '0' && two == '0' && three == '1') {
        return '1';
    }
    if (one == '0' && two == '1' && three == '0') {
        return '2';
    }
    if (one == '0' && two == '1' && three == '1') {
        return '3';
    }
    if (one == '1' && two == '0' && three == '0') {
        return '4';
    }
    if (one == '1' && two == '0' && three == '1') {
        return '5';
    }
    if (one == '1' && two == '1' && three == '0') {
        return '6';
    }
    if (one == '1' && two == '1' && three == '1') {
        return '7';
    }
}

'알고리즘 & SQL > 백준(BOJ)' 카테고리의 다른 글

백준 14753번 : MultiMax C++  (0) 2018.11.02
백준 9086번 : 문자열 C++  (0) 2018.11.02
백준 1427번 : 소트인사이드 C++  (0) 2018.11.02
백준 2851번 : 슈퍼 마리오 C++  (1) 2018.11.02
백준 10987번 : 단위 C++  (0) 2018.10.30

+ Recent posts