Given two binary strings s1 and s2 consisting of only 0s and 1s. Find the resultant string after adding the two Binary Strings. Note: The input strings may contain leading zeros but the output string should not have any leading zeros.
Examples:
Input: s1 = "1101", s2 = "111" Output: 10100 Explanation: "1101" and "111" in decimal representation will be 13 and 7 respectively. Adding both the numbers gives 20, and its binary representation is "10100".
Input: s1 = "00100", s2 = "010" Output: 110 Explanation: "00100" and "010" in decimal representation will be 4 and 2 respectively. Adding both the numbers gives 6, and its binary representation is "110".
This problem can be solved using Bit-by-bit addition with carry in O(n + m) Time and O(1) Space, 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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.