2진수가 주어졌을 때, 8진수로 변환하는 프로그램을 작성하시오.
첫째 줄에 2진수가 주어진다. 주어지는 수의 길이는 1,000,000을 넘지 않는다.
첫째 줄에 주어진 수를 8진수로 변환하여 출력한다.
비트연산을 활용해서 풀었던 문제이다.
8진수의 경우 2진수를 3단위로 나눠 계산해주면 되는데,
만약 0이 아니라면 1의 i만큼 비트 연산을 해서 더해주는 방식으로 구현했다.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = '';
rl.on('line', (line) => {
input = line;
});
rl.on('close', () => {
console.log(solution(input));
});
function solution(num) {
let input = [...num];
let answer = [];
while (input.length) {
let temp_answer = 0;
for (let i = 0; i < 3; i++) {
let temp = parseInt(input.pop());
if (!temp) continue;
temp_answer += 1 << i;
}
answer.push(temp_answer);
}
return answer.reverse().join('');
}