![]() |
VOOZH | about |
Given two binary strings s1 and s2, the task is to return their sum.The input strings may contain leading zeros but the output string should not have any leading zeros.
Example:
Input: s1 = "1101", s2 = "111"
👁 Add-two-binary-strings-using-Bit-by-Bit-addition
Output: "10100"
Explanation:Input: s1 = "00100", s2 = "010"
Output: "110"
The idea is to first trim the leading zeros in the input strings. Now, start from the last characters of the strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the next digits. Also consider this carry while calculating the digit sum. After calculating the sum, if an additional carry is generated, prepend a '1' of the result.
10100
Time Complexity: O(n + m), for traversing the strings.
Auxiliary Space: O(n), for result array as strings are immutable in most of language and O(1) in C++ where strings are mutable.
Related Articles: