[백준 | Java] 1212 8진수 2진수

알린·2024년 1월 18일

baekjoon

목록 보기
18/68

내 풀이

오답 풀이

처음엔 1373번 '2진수 8진수' 문제를 풀었을 때 처럼 진수변환하는 기능을 구현하여 변환하려 시도했다.

👉 1373번 2진수 8진수 포스팅

8진수 ➡️ 2진수 변환 과정

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        String[] octalStr = br.readLine().split("");
        int[] octalInt = new int[octalStr.length];

        for (int i = 0; i < octalStr.length; i++) {
            octalInt[i] = Integer.parseInt(octalStr[octalStr.length-1-i]);
        }

        int decimal = octalToDecimal(octalInt);
        int mod;
        while (decimal != 0) {
            mod = decimal%2;
            sb.append(mod);
            decimal = decimal/2;
        }
        
        bw.write(sb.reverse()+"\n");
        bw.flush();
        bw.close();
    }

    public static int octalToDecimal (int[] octalInt) {
        int decimal = 0;
        for (int i = 0; i < octalInt.length; i++) {
            int eight = 1;
            for (int j = 1; j <= i; j++) {
                if (i == 0)
                    break;
                eight *= 8;
            }
            decimal += octalInt[i]*eight;
        }
        return decimal;
    }
}

위의 코드로 프로그램은 잘 돌아갔지만, 시간초과로 오답이 떴다.

정답 풀이

찾아보니 진수 변환을 구현하지 않아도 Integer.toBinaryString()이라는 2진수로 변환해주는 메소드가 있기 때문에 이를 활용하면 풀리는 문제였다.

  1. 입력한 8진수를 문자열로 받아서 charAt(i) -'0'을 사용해 하나씩 쪼개기
  2. 쪼개어진 입력값을 Integer.toBinaryString()에 넣어서 변환된 2진수를 StringBuilder에 넣어주기
    => 첫 번째 입력에 대해서는 0을 제거하지 않고, 그 이후의 입력에 대해서는 출력길이가 2일 때 0을 1개 추가, 출력길이가 1일 때 0을 2개 추가

🤷‍♀️ charAt(i) -'0' 사용 이유

  • chatAt(): string 타입으로 받은 문자열을 char 타입으로 한 글자만 받게 해주는 함수
    => 숫자형 문자를 chatAt() 함수로 추출하면 char형이므로 int형으로 변환할 때 아스키코드로 변환
    👉 '0' 또는 48을 빼주어야 의도대로 계산 가능
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        String octalStr = br.readLine();

        for (int i = 0; i < octalStr.length(); i++) {
            // 문자를 숫자로 바꿔줌
            String a = Integer.toBinaryString(octalStr.charAt(i) - '0');

            if (a.length() == 2 && i != 0)
                a = "0" + a;
            else if (a.length() == 1 && i != 0)
                a = "00" + a;
            sb.append(a);
        }

        bw.write(sb+"\n");
        bw.flush();
        bw.close();
    }
}

profile
짱이 되고싶은 개발 기록

0개의 댓글