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 the 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 the 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 implementation of the above algorithm.
C++
#include <iostream> using namespace std; //adds the two-bit strings and return the result string addBitStrings( string first, string second ); // Helper method: given two unequal sized bit strings, converts them to // same length by adding leading 0s in the smaller string. Returns the // the new length int makeEqualLength(string &str1;, string &str2;) { int len1 = str1.size(); int len2 = str2.size(); if (len1 < len2) { for (int i = 0 ; i < len2 - len1 ; i++) str1 = '0' + str1; return len2; } else if (len1 > len2) { for (int i = 0 ; i < len1 - len2 ; i++) str2 = '0' + str2; } return len1; // If len1 >= len2 } // The main function that adds two-bit sequences and returns the addition string addBitStrings( string first, string second ) { string result; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(first, second); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length-1 ; i >= 0 ; i--) { int firstBit = first.at(i) - '0'; int secondBit = second.at(i) - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry)+'0'; result = (char)sum + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry) result = '1' + result; return result; } // Driver program to test above functions int main() { string str1 = "1100011"; string str2 = "10"; cout << "Sum is " << addBitStrings(str1, str2); return 0; } |
Java
// Java implementation of above algorithm class GFG { // Helper method: given two unequal sized bit strings, // converts them to same length by adding leading 0s // in the smaller string. Returns the the new length // Using StringBuilder as Java only uses call by value static int makeEqualLength(StringBuilder str1, StringBuilder str2) { int len1 = str1.length(); int len2 = str2.length(); if (len1 < len2) { for (int i = 0; i < len2 - len1; i++) str1.insert(0, '0'); return len2; } else if (len1 > len2) { for (int i = 0; i < len1 - len2; i++) str2.insert(0, '0'); } return len1; // If len1 >= len2 } // The main function that adds two-bit sequences // and returns the addition static String addBitStrings(StringBuilder str1, StringBuilder str2) { String result = ""; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(str1, str2); // Convert StringBuilder to Strings String first = str1.toString(); String second = str2.toString(); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length - 1; i >= 0; i--) { int firstBit = first.charAt(i) - '0'; int secondBit = second.charAt(i) - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry) + '0'; result = String.valueOf((char) sum) + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry == 1) result = "1" + result; return result; } // Driver Code public static void main(String[] args) { String str1 = "1100011"; String str2 = "10"; System.out.println("Sum is " + addBitStrings(new StringBuilder(str1), new StringBuilder(str2))); } } // This code is contributed by Vivek Kumar Singh |
Python3
# Python3 program for above approach # adds the two-bit strings and return the result # Helper method: given two unequal sized bit strings, # converts them to same length by adding leading 0s # in the smaller string. Returns the the new length def makeEqualLength(str1, str2): len1 = len(str1) # Length of string 1 len2 = len(str2) # length of string 2 if len1 < len2: str1 = (len2 - len1) * '0' + str1 len1 = len2 elif len2 < len1: str2 = (len1 - len2) * '0' + str2 len2 = len1 return len1, str1, str2 def addBitStrings( first, second ): result = '' # To store the sum bits # make the lengths same before adding length, first, second = makeEqualLength(first, second) carry = 0 # initialize carry as 0 # Add all bits one by one for i in range(length - 1, -1, -1): firstBit = int(first[i]) secondBit = int(second[i]) # boolean expression for sum of 3 bits sum = (firstBit ^ secondBit ^ carry) + 48 result = chr(sum) + result # boolean expression for 3 bits addition carry = (firstBit & secondBit) | \ (secondBit & carry) | \ (firstBit & carry) # if overflow, then add a leading 1 if carry == 1: result = '1' + result return result # Driver Code if __name__ == '__main__': str1 = '1100011' str2 = '10' print('Sum is', addBitStrings(str1, str2)) # This code is contributed by # chaudhary_19 (Mayank Chaudhary) |
C#
// C# implementation of above algorithm using System; using System.Text; class GFG { // Helper method: given two unequal sized // bit strings, converts them to same length // by adding leading 0s in the smaller string. // Returns the the new length Using StringBuilder // as Java only uses call by value static int makeEqualLength(StringBuilder str1, StringBuilder str2) { int len1 = str1.Length; int len2 = str2.Length; if (len1 < len2) { for (int i = 0; i < len2 - len1; i++) { str1.Insert(0, '0'); } return len2; } else if (len1 > len2) { for (int i = 0; i < len1 - len2; i++) { str2.Insert(0, '0'); } } return len1; // If len1 >= len2 } // The main function that adds two-bit sequences // and returns the addition static string addBitStrings(StringBuilder str1, StringBuilder str2) { string result = ""; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(str1, str2); // Convert StringBuilder to Strings string first = str1.ToString(); string second = str2.ToString(); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length - 1; i >= 0; i--) { int firstBit = first[i] - '0'; int secondBit = second[i] - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry) + '0'; result = ((char) sum).ToString() + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry == 1) { result = "1" + result; } return result; } // Driver Code public static void Main(string[] args) { string str1 = "1100011"; string str2 = "10"; Console.WriteLine("Sum is " + addBitStrings(new StringBuilder(str1), new StringBuilder(str2))); } } // This code is contributed by kumar65 |
Output:
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Inserting m into n such that m starts at bit j and ends at bit i.
- Inserting M into N such that m starts at bit j and ends at bit i | Set-2
- Count of 1-bit and 2-bit characters in the given binary string
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Pairs of complete strings in two sets of strings
- Count of binary strings of length N with even set bit count and at most K consecutive 1s
- Add n binary strings
- Check if two numbers are bit rotations of each other or not
- Position of rightmost common bit in two numbers
- Check whether the two numbers differ at one bit position only
- Position of rightmost bit with first carry in sum of two binary
- Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes
- Find position of left most dis-similar bit for two numbers
- Find average of two numbers using bit operation
- Add two numbers without using arithmetic operators
- Count binary strings with k times appearing adjacent two set bits
- Check if concatenation of two strings is balanced or not
- Given two binary strings perform operation until B > 0 and print the result
- Find uncommon characters of the two strings | Set 2
- XOR two binary strings of unequal lengths

