Add Binary

Easy Bit Manipulation AI round

a and b are two whole numbers, neither negative, written in binary: as strings of the digits 0 and 1, the most significant digit first.

Return their sum, written the same way in binary, with no 0 in front unless the sum is 0.

Example 1

Input: a = "1101", b = "111"
Output: "10100"

In tens these are 13 + 7 = 20. Column by column from the right: 1 + 1 is 10, so 0 and carry 1; 0 + 1 + 1 is 10 again; 1 + 1 + 1 is 11, so 1 and carry 1; 1 + 1 is 10; the last carry makes 10100.

Example 2

Input: a = "0", b = "1001"
Output: "1001"

Example 3

Input: a = "1111", b = "1111"
Output: "11110"

Constraints

  • 1 ≤ a.length, b.length ≤ 2 × 10⁴
  • a and b hold only the characters 0 and 1
  • Neither has a 0 in front, but the number 0 itself, written 0

More Bit Manipulation

All Bit Manipulation problems