십진수와 이진수 2

정민교·2024년 2월 7일
0

자료구조&알고리즘

목록 보기
4/10

십진수와 이진수 2

일반적인 10진수와 2진수 변환 문제이다.

여기서는 2진수를 10진수로 변환하여 17배를 하고 다시 2진수로 변환하여 출력한다.

2진수를 10진수로 변환하는 방법은 앞서 소개한 더블-더블 방법을 사용하였다.

import java.io.*;
import java.util.*;
import java.util.stream.*;

public class Main {
    public static List<Integer> answer = new ArrayList<>();
    public static StringBuilder sb = new StringBuilder();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        List<Integer> inputBinary = Arrays.stream(br.readLine().trim().split("")).map(Integer::parseInt).collect(Collectors.toCollection(ArrayList::new));

        int decimal = 0;
        for (Integer ele : inputBinary) {
            decimal = decimal * 2 + ele;
        }
        decimal *= 17;

        while (true) {
            if (decimal < 2) {
                answer.add(decimal);
                break;
            }
            answer.add(decimal % 2);
            decimal /= 2;
        }
        Collections.reverse(answer);
        answer.stream().forEach(sb::append);
        System.out.println(sb);
        br.close();
    }
}
profile
백엔드 개발자

0개의 댓글