This is a packet that returns the sum of 2 binary strings as a binary string using C++.
In this program, given two binary strings, we return their sum which is also a binary string.
Examples:
1) Input: a="101" b="100"
Output: 1001
2) Input: a="101" b="11"
Output: 1000
Rules of Binary Addition:
a) 0+0 = 0, carry = 0
b) 1+0 = 1, carry = 0
c) 0+1 = 1, carry = 0
d) 1+1 = 0, carry = 1
Algorithm:
1. Initialise a string that stores the result. Declare a sum variable that stores the sum.
2. Take two binary strings as input. Traverse both the strings starting from their ends. Compute sum and carry.
3. If the sum is 2, carry is 1. Hence, Carry = sum/2.
3. Reverse the string and return it.
Submitted by Shravya Chinta (shravyachinta)
Download packets of source code on Coders Packet
Comments