
Sponsored
Sponsored
This method involves simulating the addition process as if one were adding numbers on paper. We traverse both strings from the least significant bit to the most, adding corresponding bits and maintaining a carry as needed. If the carry is still 1 after processing both strings, it is added to the result.
Time Complexity: O(max(N, M)) where N and M are the lengths of strings a and b. The space complexity is also O(max(N, M)) to store the result.
1def addBinary(a: str, b: str) -> str:
2 result = []
3 carry = 0
4 i, j = len(a) - 1, len(b) - 1
5
6 while i >= 0 or j >= 0 or carry:
7 sum = carry
8 if i >= 0: sum += int(a[i]); i -= 1
9 if j >= 0: sum += int(b[j]); j -= 1
10 result.append(str(sum % 2))
11 carry = sum // 2
12 return ''.join(reversed(result))
13
14print(addBinary("1010", "1011"))The Python approach uses a list to collect the binary digits in reverse order, iterating through the digits of both inputs from end to start, considering each bit sum with a carry. After iteration, we reverse and join the list to get the binary sum.
This approach leverages built-in support for manipulating large integers available in many programming languages. By converting binary strings to integers, performing arithmetic operations, and then converting the result back to binary format, we can simplify the computation.
Time Complexity: O(N + M), due to integer conversion and addition operations. Space Complexity: O(N + M) for storing integer representations.
1public class AddBinary {
2
In this Java solution, the Integer.parseInt method is used to convert binary strings to integers. The integers are added and the result is converted back to binary using Integer.toBinaryString.