Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created January 26, 2026 23:58
Show Gist options
  • Select an option

  • Save Ephraimiyanda/204161574e45ad5f11bfb50f1a5f615d to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/204161574e45ad5f11bfb50f1a5f615d to your computer and use it in GitHub Desktop.
Add Binary

Question

Approach

  1. using binary addition i start adding from the least significant bit at the endof the string.
  2. carry variable stores overload from addition of bits in binary and adds it to the sum of the nexts bits while the loop continues.
  3. remainder of bits is added to the end of a result array which is returned as a string

Complexity

  • Time complexity:O(Max(A,B))

  • Space complexity:O(Max(A,B))

Code

function addBinary(a: string, b: string): string {
    let i = a.length - 1;
    let j = b.length - 1;
    let carry = 0;
    let result = [];

    while (i >= 0 || j >= 0 || carry) {
        let sum = carry;

        if (i >= 0) sum += Number(a[i--]);
        if (j >= 0) sum += Number(b[j--]);

        result.unshift(sum % 2);
        carry = Math.floor(sum / 2);
    }

    return result.join("");
}
scrnli_853572rO9TUjkj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment