DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

Add Binary

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:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        m = len(a)
        n = len(b)
        if m > n:
            b = "0" * (m - n) + b
        else:
            a = "0" * (n - m) + a
        op = []
        k = max(m, n)
        i = k - 1
        carry = 0
        while i >= 0:
            currval = int(a[i]) + int(b[i]) + carry
            op.append(str(currval % 2))
            carry = currval // 2
            i -= 1
        return "1" * carry + "".join(op[::-1])
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay