LeetcodeApr 11, 2025

Add Binary

Hazrat Ali

Leetcode

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"

 

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} s1
 * @param {string} s2
 * @return {string}
 */
const addBinary = (s1, s2) => {
  let i = s1.length - 1;
  let j = s2.length - 1;
  let c = 0;
  let s = '';

  while (i >= 0 || j >= 0 || c > 0) {
    const a = i < 0 ? 0 : s1[i--] - '0';
    const b = j < 0 ? 0 : s2[j--] - '0';

    s = (a ^ b ^ c) + s;
    c = (a + b + c) >> 1;
  }

  return s;
};

 

 

 

Comments