Learn-dsa..in 30 days!



























CC-2 : Add 2 Binary Strings represented as Strings.

Description:

Given two input Strings, containing binary numbers represented as Strings, add the numbers using binary addition logic and return the sum.

Test cases and expected outputs:

Input Parameters Expected outputs
String str1= "1010";
String str2="10101";
011111
str1= "10101";
str2="101";
011010
str1= "11111";
str2="11111";
111110
str1= "00000";
str2="11111"
011111

Pseudocode:

The java method should accept following input parameters: str1 (String), str2(String). str1 and str2 represent binary numbers, so the strings contain only 0 and 1 characters.
Extract the characters from str1 and str2 into char arrays bin1 and bin2.
Find the length of str1 and str2, set int variable max to hold the max of the two lengths and create a new char array named sum and with length equal to max, to hold the result of binary addition of str1 and str2.
Mimicking manual binary numbers addition, we will add the input binary numbers column by column, and store the first digit of sum (from right) of in char array sum and carry over the second digit of addition to the next column to be added.
Declare a variable carry to hold the carry over value (to be added to next column), when 2 binary numbers of a column are added as part of binary addition operation. Also initialize variable bin1idx to (bin1.length-1) and variable bin2idx to (bin2.length-1). We will use these 2 variables to do addition column-wise starting from the rightmost binary dights in bin1 and bin2.
Define a method binsum(), which takes 2 binary digits and a carry digit as inputs and returns the first digit of sum (from left) and resulting carry value needed for next column addition.
Iterate through sum using for loop using idx as loop variable, starting from index max-1 and decrementing idx till we reach index 0:
If b1idx and b2idx are less than or equal to -1, we have iterated adding columns from right to left, except leftmost column. Call binsum() with inputs 0, 0, carry to calculate binary sum for left most column.
If only b1idx is less than or equal to -1, it means bin1 is a shorter binary number than bin2. Call binsum() with inputs 0, bin1[b1idx], carry to calculate binary sum for current column.
If only b2idx is less than or equal to -1, it means bin2 is a shorter binary number than bin1. Call binsum() with inputs bin2[b2idx], 0, carry to calculate binary sum for current column.
If none of above if conditions are matched, binsum() with inputs bin1[bin1idx], bin2[b2idx], carry to calculate binary sum for current column.
Set sum[idx] to sum value returned by binsum(). The carry value returned by binsum() will be used in next iteration of binary addition.
o Decrement bin1idx and bin2idx by 1.
After above loop has completed sum contains the result of binary addition. Return sum.

binsum() method:

The java method should accept following input parameters: c1 (char), c2 (char), and carry(char).
Declare a char array retVal with length 2. retval[0] will hold the first digit of sum (from right) of c1 and c2. retval[1] will hold carry value resulting from binary addition of c1 and c2.
Parse integers from c1, c2 and c3 and add the same and store result in variable named sum.
Based on rules of binary addition of two binary numbers:
If the sum is 0, set retVal[0] to ‘0’ and retVal[1] to ‘0’.
If the sum is 1, set retVal[0] to ‘1’ and retVal[1] to ‘0’.
If the sum is 2, set retVal[0] to ‘0’ and retVal[1] to ‘1’.
If the sum is 3, set retVal[0] to ‘1’ and retVal[1] to ‘1’.
Return retVal.

Code:

public String stringAddBinaryStrings(String str1, String str2) {
	char[] bin1=str1.toCharArray(); 
	char[] bin2=str2.toCharArray();
	int b1idx=bin1.length-1; int b2idx=bin2.length-1;
	char[] retVal; 
	int max=0; char carry='0'; char sumColumn='0';
	if (b1idx > b2idx) {
		max=bin1.length+1;
	} else {
		max=bin2.length+1;
	}
	char[] sum=new char[max];
	for (int idx=max-1; idx >=0 ; idx--) {
		if ((b1idx <= -1)&& (b2idx <=-1)){
			retVal=binsum('0','0', carry);	
		}else {
		if (b1idx<=-1) {
			retVal=binsum('0',bin2[b2idx], carry);			
		}else {
		if (b2idx<=-1) {
			retVal=binsum(bin1[b1idx],'0',carry);			
		}else {
			retVal=binsum(bin1[b1idx],bin2[b2idx],carry);	
		}
		}
		}
		sumColumn=retVal[0]; carry=retVal[1];
		sum[idx]=sumColumn;
		b1idx--;b2idx--;
	}
	return new String(sum);
}

public char[] binsum(char c1, char c2, char carry){
	int bit1=Integer.parseInt(""+c1+"");
	int bit2=Integer.parseInt(""+c2+"");
	int cbit=Integer.parseInt(""+carry+"");
	//System.out.println(bit1+" "+bit2+" "+cbit);
	char[] retVal=new char[2];
	int sum=bit1+bit2+cbit;
	if (sum==0) {
		retVal[0]='0'; retVal[1]='0';
	}
	if (sum==1) {
		retVal[0]='1'; retVal[1]='0';
	}
	if (sum==2) {
		retVal[0]='0'; retVal[1]='1';
	}
	if (sum==3) {
		retVal[0]='1'; retVal[1]='1';
	}
	return retVal;
}

Click here to download and run code and test cases !