본문 바로가기
LeetCode/코딩 테스트 스터디 3주차

[LeetCode] 67. Add Binary 풀이 (JS)

by inwoo1324 2022. 7. 24.

0. 문제

https://leetcode.com/problems/add-binary/

 

Add Binary - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

두 개의 이진 문자열 a 및 b가 주어지면 그 합계를 이진 문자열로 반환합니다 .

#1
Input: a = "11", b = "1"
Output: "100"
#2
Input: a = "1010", b = "1011"
Output: "10101"

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

var addBinary = function(a, b) {
    var result = String(),
        value = 0;
  	a = '0'.repeat(b.length - a.length > 0 ? b.length - a.length : 0) + a;
    b = '0'.repeat(a.length - b.length > 0 ? a.length - b.length : 0) + b;

    for (let i = a.length-1; i >= 0; i--){
        value = Number(a[i]) + Number(b[i]) + value
        if (value > 1){
            value -= 2;
            result = String(value) + result;
            value = 1;
        } else {
            result = String(value) + result;
            value = 0;
        }
    }
    
    if (value) result = '1' + result;
    
    return result
};
Runtime: 97 ms, faster than 51.97% of JavaScript online submissions for Add Binary.
Memory Usage: 44.1 MB, less than 33.81% of JavaScript online submissions for Add Binary.

이진수 덧셈이라 쉽게 풀었던 문제

각 String이 길이가 다를 수 있으므로 빈 수만큼 0을 붙히고 반복문으로 해결했다.