Add Binary — LeetCode 67 Python Solution
EasyBit ManipulationMathStringSimulation
- Problem
- #67
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two binary strings a and b, return their sum as a binary string.
Example
- Input
- a = "11", b = "1"
- Output
- "100"
Python solution
Python
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])Complexity
| Measure | Complexity |
|---|---|
| Time | O(\max(m, n)), where m and n are the lengths of strings a and b respectively |
| Space | O(1) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 67. Add Binary is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
LeetCode 405Convert a Number to HexadecimalEasyLeetCode 1404Number of Steps to Reduce a Number in Binary Representation to OneMediumLeetCode 1680Concatenation of Consecutive Binary NumbersMediumLeetCode 29Divide Two IntegersMediumLeetCode 231Power of TwoEasyLeetCode 318Maximum Product of Word LengthsMedium
On study lists
This problem is on Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 67. Add Binary?
- LeetCode 67. Add Binary is rated Easy on LeetCode.
- What is the time complexity of LeetCode 67. Add Binary?
- The Python solution on this page runs in O(\max(m, n)), where m and n are the lengths of strings a and b respectively.
- What is the space complexity of LeetCode 67. Add Binary?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 67. Add Binary cover?
- LeetCode 67. Add Binary is tagged Bit Manipulation, Math, String and Simulation on LeetCode.