이진수를 의미하는 두 개의 문자열 bin1과 bin2가 매개변수로 주어질 때, 두 이진수의 합을 return하도록 solution 함수를 완성해주세요.
ex) bin1 = "10", bin2 = "11", result = "101"
10을 십진수로 바꾸면 2, 11을 십진수로 바꾸면 3이므로 둘의 합은 5가 된다. 5는 이진수로 101이므로 101을 return 한다.
bin1과 bin2를 각각 십진수로 바꿔서 더한 후에 이진수로 바꾸기
function solution(bin1, bin2) {
return (parseInt(bin1,2) + parseInt(bin2,2)).toString(2);
}
⭐️ 이진수를 십진수로 바꾸기
parseInt(binary, 2)
https://masteringjs.io/tutorials/tools/binary-to-decimal
⭐️ 십진수를 이진수로 바꾸기
decimal.toString(2)
https://www.programiz.com/javascript/examples/decimal-binary
function solution(bin1, bin2) {
let temp = Number(bin1) + Number(bin2);
temp = [...temp.toString()].reverse().map((v) => +v);
for (let i = temp.length; i < 11; i++) {
temp.push(0);
}
for (let i = 0; i < temp.length; i++) {
if (temp[i] === 2) {
temp[i] = 0;
temp[i + 1]++;
} else if (temp[i] === 3) {
temp[i] = 1;
temp[i + 1]++;
}
}
return Number(temp.reverse().join("")).toString();
}