본문 바로가기

백준

1373 2진수 8진수

음.. 

코드가 더럽다..

어떻게 할지 몰라서 그냥 사람이 하는 그대로 코딩했다. 

8진수로 보통 3자리씩 끊어 읽기 때문에 3의 배수로 길이를 맞춰준다.

다음으로 각 자리수를 계산한다. 마지막으로 계산한 8진수를 문자열에 붙여준다. 끝~!

#include <iostream>

using namespace std;

int main() {
    string str;
    cin >> str;
    if ((3 - (str.length() % 3)) == 1)
        str = "0" + str;
    else if ((3 - (str.length() % 3)) == 2)
        str = "00" + str;
        
    string result = "";
    int sum = 0;
    
    for(int i = 0; i < str.length(); i++){
        if(i%3 == 0)
            sum += 4*(str[i] - '0');
        else if(i%3 == 1)
            sum += 2*(str[i] - '0');
        else{
            sum += (str[i] - '0');
            result += (sum + '0');
            sum = 0;
        }
    }
    cout << result;
}

어쩔 수가 없었다.. 내 생각이 여기까지 인거슬..

 


 

 

#include <iostream>

using namespace std;

int main() {
    string str;
    cin >> str;
    if ((3 - (str.length() % 3)) == 1)
        str = "0" + str;
    else if ((3 - (str.length() % 3)) == 2)
        str = "00" + str;
        
    string result = "";
    
    for(int i = 0; i < str.length(); i += 3){
        //int d = 4*(str[i]-'0') + 2*(str[i+1]-'0') + str[i + 2]-'0';
        int d = 4 * str[i] + 2 * str[i + 1] + str[i+2] - 7 * '0';
        result += d + '0';
    }
    cout << result;
}

zz 처음부터 세자리씩 자리 맞췄으니깐 세자리 씩 읽는게 더 깔끔하다. 

 

int d = 4 * str[i] + 2 * str[i + 1] + str[i+2] - 7 * '0';

 

처음에 이거 보고 왜 7*'0'을 빼는지 몰라서 아래와 같이 코딩했다. 

 

int d = 4*(str[i]-'0') + 2*(str[i+1]-'0') + str[i + 2]-'0';

 

알고보니 그냥 저 식 풀면 위의 식이 된다. 

 

 

'백준' 카테고리의 다른 글

5586 JOI와 IOI  (0) 2019.10.11
11718 그대로 출력하기  (0) 2019.10.11
7567 그릇  (0) 2019.10.09
6539 만취한 상범  (0) 2019.10.09
1037 약수  (0) 2019.10.09