
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.
1public class AddBinary {
2 public static String addBinary(String a, String b) {
3 StringBuilder result = new StringBuilder();
4 int carry = 0, aLen = a.length(), bLen = b.length();
5 int maxLength = Math.max(aLen, bLen);
6
7 for (int i = 0; i < maxLength; i++) {
8 int aBit = (i < aLen) ? a.charAt(aLen - 1 - i) - '0' : 0;
9 int bBit = (i < bLen) ? b.charAt(bLen - 1 - i) - '0' : 0;
10 int sum = aBit + bBit + carry;
11 carry = sum / 2;
12 result.append(sum % 2);
13 }
14 if (carry != 0) result.append(carry);
15 return result.reverse().toString();
16 }
17
18 public static void main(String[] args) {
19 System.out.println(addBinary("1010", "1011"));
20 }
21}Using a StringBuilder to efficiently construct the resulting string, this Java implementation processes each bit position starting from the end of the input strings to the start, considering current bits and a carry, then reverses and returns the string.
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.
1def addBinary(a: str, b:
This Python solution uses the int function to convert binary strings to integers, adds them, and converts the sum back to binary format using the bin function, stripping the '0b' prefix with slicing.