
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.
1function addBinary(a, b) {
2 let carry = 0,
3 result = [];
4 let i = a.length - 1, j = b.length - 1;
5 while (i >= 0 || j >= 0 || carry) {
6 let sum = carry;
7 if (i >= 0) sum += a[i--] - '0';
8 if (j >= 0) sum += b[j--] - '0';
9 result.push(sum % 2);
10 carry = Math.floor(sum / 2);
11 }
12 return result.reverse().join('');
13}
14console.log(addBinary("1010", "1011"));The JavaScript function builds an array of binary digits by examining characters from the ends of the input strings, manages a carry, and creates the result array. The array is then reversed and joined to form the final binary 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.
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.