PS/문자열 알고리즘[String]

백준 1212 8진수 2진수(c++)

SeungbeomKim 2022. 7. 6. 19:43
반응형

https://www.acmicpc.net/problem/1212

 

1212번: 8진수 2진수

첫째 줄에 8진수가 주어진다. 주어지는 수의 길이는 333,334을 넘지 않는다.

www.acmicpc.net

<코드>

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

string eight[8] = {"000","001","010","011","100","101","110","111"};

int main(){
    string s;
    cin >> s;
    if(s=="0") cout<<"0";
    string ans = "";
	bool start = true;
	
    for (int i=0; i<s.length(); i++) 
    {
        int n = s[i]-'0';
        
        if (start == true && n < 4) 
        {
            if (n == 0)
                continue;
            else if(n == 1)
                ans +="1";
            else if (n == 2) 
                ans +="10";
            else if (n == 3)
                ans +="11";
                
            start = false;
        } 
        else 
        {
            ans += eight[n];
            start = false;
        }
    }
    cout<<ans;
}

<풀이과정>

빈 문자열 ans을 선언하고, 가장 왼쪽 3비트가 4보다 작을 때만 각각 0(continue), 1, 10, 11을 더해주면 된다. 왜냐하면 그 이후 비트에는 3비트에서 0이 언제 들어와도 상관없기 때문이다. 

더불어 자료형이 bool인 변수를 선언해주어야 되는데, 가장 왼쪽 3비트가 맞는지 아닌지를 검사하기 위한 변수라고 생각하면 더욱 이해하기 편하다. 

반응형

'PS > 문자열 알고리즘[String]' 카테고리의 다른 글

백준 1431 시리얼 번호(c++)  (1) 2022.07.08
백준 11656 접미사 배열(c++)  (1) 2022.07.08
백준 1373 2진수 8진수(c++)  (0) 2022.07.06
백준 14425 문자열 집합(c++)  (0) 2022.07.06
백준 5525 IOIOI(c++)  (0) 2022.07.05