► JS Algorithm/Programmers
[Programmers] JavaScript 알고리즘 | Lv.0 이진수 더하기
다람트리
2024. 8. 20. 00:08
반응형
🔒 문제 설명
이진수를 의미하는 두 개의 문자열 bin1과 bin2가 매개변수로 주어질 때, 두 이진수의 합을 return하도록 solution 함수를 완성해주세요.
🔒 제한사항
- return 값은 이진수를 의미하는 문자열입니다.
- 1 ≤ bin1, bin2의 길이 ≤ 10
- bin1과 bin2는 0과 1로만 이루어져 있습니다.
- bin1과 bin2는 "0"을 제외하고 0으로 시작하지 않습니다.
🔒 입출력 예
bin1 | bin2 | result |
"10" | "11" | "101" |
"1001" | "1111" | "11000" |
🔒 입출력 예 설명
입출력 예 #1
- 10 + 11 = 101 이므로 "101" 을 return합니다.
입출력 예 #2
- 1001 + 1111 = 11000 이므로 "11000"을 return합니다.
🔐 solution of mine
parseInt()
Number.prototype.toString()
function solution(bin1, bin2) {
return console.log((parseInt(bin1, 2) + parseInt(bin2, 2)).toString(2));
}
solution("10", "11"); // expected output: "101"
solution("1001", "1111"); // expected output: "11000"
◆ 해설집 - 특정 진수로 변환하는 방법
2진수 → 10진수 | parseInt(2진수, 2) |
10진수 → 2진수 | 10진수.toString(2) |
... js에서 진수를 바꾸는 함수가 존재하지만,
나중에 다른언어를 공부할때는 아래의 풀이처럼
진수를 직접 바꾸는 풀이를 할 줄 알아야할 것 같다.
역시나... 진수 구하는 수학적인 지식이 부족함으로......
이해하기위해서는 추후에 복습이 필요한 풀이이다.
🔐 solution of others
Number.prototype.toString()
Array.prototype.reverse()
Array.prototype.map()
Array.prototype.push()
Array.prototype.join()
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();
}
🔐 solution of others
String.prototype.split()
Array.prototype.reverse()
Array.prototype.push()
Math.floor()
Array.prototype.join()
function solution(_bin1, _bin2) {
const bin1 = _bin1.split("").reverse();
const bin2 = _bin2.split("").reverse();
const N1 = bin1.length;
const N2 = bin2.length;
let i = 0;
let j = 0;
let sum = 0;
let carry = 0;
let result = [];
while (i < N1 || j < N2 || carry > 0) {
const n1 = Number(bin1[i]) || 0;
const n2 = Number(bin2[j]) || 0;
let localSum = carry + n1 + n2;
result.push(localSum % 2);
carry = Math.floor(localSum / 2);
i += 1;
j += 1;
}
return result.reverse().join("");
}
반응형