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

알린·2024년 1월 17일

baekjoon

목록 보기
17/68

내 풀이

기능 완전 구현 방식

  • 2진수 ➡️ 8진수
  1. 2진수를 split("")을 사용해 String형 배열에 한 글자씩 삽입
  2. String형 배열을 int형 배열로 형변환하여 queue에 해당 배열 원소들 삽입
  3. 입력받은 2진수를 3칸씩 나누었을 때 딱 나누어 떨어지지 않는다면, 가장 앞자리 1~2칸은 0을 대입하여 진수변환을 해야하므로 if문으로 3으로 나누었을 때 결과에 따라 다른 알고리즘 작성 (아래 예시)
  4. 2진수에서 8진수로 변환해주는 메소드를 작성

3번 예시

2진수: 111 001 100
queue.size() == 9
9/3 = 3 => 0이 필요없음

2진수: 11 001 100
queue.size() == 8
8/3 = 2 ... 2 => 0이 1개필요

2진수: 1 001 100
queue.size() == 7
7/2 = 2 ... 1 => 0이 2개필요

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static StringBuilder sb = new StringBuilder();
    public static Queue<Integer> queue = new LinkedList<>();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] arrStr = br.readLine().split("");
        int[] arrInt = new int[arrStr.length];

        for (int i = 0; i < arrStr.length; i++) {
            arrInt[i] = Integer.parseInt(arrStr[i]);
            queue.add(arrInt[i]);
        }

        if (queue.size()%3 == 0) {
            binaryToOctal(queue);
        } else if (queue.size()%3 == 1){
            sb.append(queue.poll());
            binaryToOctal(queue);
        } else {
            sb.append(queue.poll()*2+queue.poll());
            binaryToOctal(queue);
        }
        System.out.println(sb);
    }

    public static void binaryToOctal (Queue<Integer> queue) {
        int size = queue.size();

        // 2진수를 3씩 묶은 칸 수 만큼 반복 진행
        for (int i = 0; i < size/3; i++) {
            int[] tmp = new int[3];
            int result = 0;

            //한 칸 내에서 j의 수에 따라 연산 수행
            for (int j = 0; j < 3; j++) {
                tmp[j] = queue.poll();
                if (j == 0)
                    result += tmp[j]*4;
                else if (j == 1)
                    result += tmp[j]*2;
                else
                    result += tmp[j];
            }
            sb.append(result);
        }
    }
}

메소드 이용 방식

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class Main {
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String S = br.readLine();
		
		//형변환을 해주면서 옆에 2를 적어주면 10진수로 바꿔준다.
		BigInteger N = new BigInteger(S, 2);
		
		//BigInteger.toString이 String으로 형변환 해주는 것이고, 옆에 괄호안에 원하는 진수를 적어주면 된다.
		String result = N.toString(8);
		
		System.out.println(result);
	}

}
profile
짱이 되고싶은 개발 기록

0개의 댓글