Given two bit sequences as strings, write a function to return the addition of the two sequences. Bit strings can be of different lengths also. For example, if string 1 is “1100011” and second string 2 is “10”, then the function should return “1100101”.
We strongly recommend that you click here and practice it, before moving on to the solution.
Since sizes of two strings may be different, we first make the size of a smaller string equal to that of the bigger string by adding leading 0s. After making sizes same, we one by one add bits from rightmost bit to leftmost bit. In every iteration, we need to sum 3 bits: 2 bits of 2 given strings and carry. The sum bit will be 1 if, either all of the 3 bits are set or one of them is set. So we can do XOR of all bits to find the sum bit. How to find carry – carry will be 1 if any of the two bits is set. So we can find carry by taking OR of all pairs. Following is step by step algorithm.
1. Make them equal sized by adding 0s at the beginning of smaller string.
2. Perform bit addition
…..Boolean expression for adding 3 bits a, b, c
…..Sum = a XOR b XOR c
…..Carry = (a AND b) OR ( b AND c ) OR ( c AND a )
Following is C++ implementation of the above algorithm.
Sum is 1100101
This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Pairs of complete strings in two sets of strings
- Add n binary strings
- Bitwise AND of N binary strings
- Count strings with consecutive 1's
- Find uncommon characters of the two strings | Set 2
- Check if concatenation of two strings is balanced or not
- Generate all the binary strings of N bits
- Generate all binary strings from given pattern
- Pairs of strings which on concatenating contains each character of "string"
- Count of non-overlapping sub-strings "101" and "010" in the given binary string
- Count binary strings with twice zeros in first half
- Count number of binary strings without consecutive 1's
- Number of Binary Strings of length N with K adjacent Set Bits
- Find the number of binary strings of length N with at least 3 consecutive 1s
- Generate all binary strings of length n with sub-string "01" appearing exactly twice
Improved By : Akanksha_Rai