[알고리즘] LeetCode - Add Binary

Jerry·2021년 1월 27일
0

LeetCode

목록 보기
20/73
post-thumbnail

LeetCode - Add Binary

문제 설명

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

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

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.

Solution

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
let addBinary = function(a, b) {
    
    let i=a.length-1;
    let j=b.length-1;

    let carrige=0;
    let sum='';
    for(; i>=0 || j>=0; ){

        let subSum=carrige;
        if(i>=0){
            subSum=subSum+(a[i] -'0');
            i--;
        }
        if(j>=0){
            subSum=subSum+(b[j]-'0');
            j--;
        }

        if(subSum>1){
            carrige=1;
            subSum=subSum%2;
        }
        else{
            carrige=0;
        }
        sum=subSum+sum;
    }
    if(carrige>0){
        sum='1'+sum;
    }
    return sum;
};

~.~

profile
제리하이웨이

0개의 댓글