LeetCode 0067. Add Binary Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0067. Add Binary

Description

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.

Solutions

Solution 1: Simulation

We use a variable carry to record the current carry, and two pointers i and j to point to the end of a and b respectively, and add them bit by bit from the end to the beginning.

The time complexity is O(max(m, n)), where m and n are the lengths of strings a and b respectively. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#
class Solution: def addBinary(self, a: str, b: str) -> str: ans = [] i, j, carry = len(a) - 1, len(b) - 1, 0 while i >= 0 or j >= 0 or carry: carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) carry, v = divmod(carry, 2) ans.append(str(v)) i, j = i - 1, j - 1 return "".join(ans[::-1])(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !