Add to List
Share
Given two binary strings a and b, return their sum as a binary string.
Example 1:
- Input: a = "11", b = "1"
- Output: "100"
Example 2:
- Input: a = "1010", b = "1011"
- Output: "10101"
1 <= a.length, b.length <= 10^4
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.
function solution(a,b){
const tenA= parseInt(a,2)
const tenB=parseInt(b,2);
const sum = tenA+tenB;
return sum.toString(2);
}
parseInt와 toString의 2진법, 10진법으로의 변환을 사용하고, 이를 통해 정답을 구하는 것을 처음에 생각했다. 하지만 제한사항에 a.length, b.length <=10^4으로 parseInt는 [2,36]자리 수에 대해서만 계산이 가능하였다.
function solution(a, b) {
let str = '';
let carry = 0;
let aPath = a.length - 1;
let bPath = b.length - 1;
while (aPath >= 0 || bPath >= 0) {
let aStr = a[aPath] ? Number(a[aPath]) : 0;
let bStr = b[bPath] ? Number(b[bPath]) : 0;
const sum = carry + aStr + bStr;
carry = Math.floor(sum / 2);
let dig = sum % 2;
str = dig + str;
aPath--;
bPath--;
}
if (carry === 1) str = carry + str;
return str;
}
a와 b를 첫자리수 부터 하나하나 더하고, 2진수의 덧셈이기 때문에 2가 넘어간다면, carry, 더한 한자리 값은 dig로 선언하고, 결과값 str에 dig를 붙여 나간다. 마지막에도 carry에 값이 있다면, str에 한번 더 붙여줌을 통해서 str을 정확하게 구할 수 있다. 이 때 while의 조건 은 aPath와 bPath가 하나라도 남아있으면 계속 되어야 하기 때문에 aPath>=0 || bPath>=0이 된다.
여전히 제한사항을 정확히 보지 않아, 다른 방식으로 문제를 푸는 일들이 있었지만, 덧셈,뺄셈 곱셈을 직접 계산해보는 좋은 기회였다.