Intuition
The problem involves adding two binary numbers represented as strings. My first thought was to convert the binary strings into integers, perform the addition, and then convert the result back into a binary string. Python's built-in functions make this process straightforward.
Approach
Convert Binary Strings to Integers:
- Use
int(a, 2)
andint(b, 2)
to convert the binary stringsa
andb
into integers.
- Use
Add the Integers:
- Perform the addition directly using
+
.
- Perform the addition directly using
Convert the Sum Back to Binary:
- Use
format(sum, 'b')
to convert the result into a binary string without the0b
prefix.
- Use
This approach leverages Python's built-in functions for efficient conversion and formatting, eliminating the need for manual binary arithmetic.
Complexity
Time complexity:
$$O(n + m)$$
Where (n) and (m) are the lengths of the binary stringsa
andb
. The conversions (int
andformat
) operate in linear time with respect to the string lengths.Space complexity:
$$O(n + m)$$
Additional space is used for storing the converted integers and the resulting binary string.
Code
class Solution(object):
def addBinary(self, a, b):
return format(int(a, 2) + int(b, 2), 'b')
Example Test Cases
Input:
a = "11", b = "1"
Output:"100"
Explanation: The binary addition of11
and1
results in100
.Input:
a = "1010", b = "1011"
Output:"10101"
Explanation: The binary addition of1010
and1011
results in10101
.Input:
a = "0", b = "0"
Output:"0"
Explanation: The binary addition of0
and0
results in0
.
Connect with Me
If you found this solution helpful, feel free to connect with me on LinkedIn! Let’s grow and share knowledge together. 😊