[Easy] 67. Add Binary

문제

Given two binary strings a and b, return their sum as a binary string.

두 개의 이진 문자열 a와 b가 주어지면, 합을 이진 문자열로 반환한다.

 

예시

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

 

제약 조건

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

 

해결 과정

처음 시도에는 BigInt 없이 풀었다가 큰 수가 들어오면 정확하게 계산을 하지 못한다.

BigInt를 사용하니 간단하게 해결 되었다.

 

해결 코드

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    return (BigInt(`0b${a}`) + BigInt(`0b${b}`)).toString(2);
};

'leetCode' 카테고리의 다른 글

[Easy] 58. Length of Last Word  (0) 2022.06.17
[Medium] 739. Daily Temperatures  (0) 2022.06.17
[Easy] 989. Add to Array-Form of Integer  (2) 2022.06.15
[Medium] 1367. Linked List in Binary Tree  (0) 2022.06.15
[Medium] 43. Multiply Strings  (0) 2022.06.15