Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MyCloud University Libraries Implement a Java method named addBinary() that take

ID: 3586202 • Letter: M

Question

MyCloud University Libraries Implement a Java method named addBinary() that takes two String arguments (each representing a binary value) and returns a new String corresponding to the result of performing binary addition on those arguments. Before you begin, if one of the arguments is shorter than the other, call your pad () method from the previous step to extend it to the desired length. Suggested pseudocode: carry_bit - o if (operand 1 is shorter than operand 2): else if (operand_2 is shorter than operand 1): for index from (length of operand 1-1) down through 0: pad operand_1 to the length of operand 2 pad operand_2 to the length of operand 1 if (carry bit+ (value of operand_1lindex]) + (value of operand 2lindex))0: sum "O" + sum carry-bit = 0 sum "1"sum carry bit 0 sum = "O" + sum carry bit - 1 sum·"1" + sum carry bit 1 else if (carry-bit + (value of operand-1 (index)) + (value of operand-2(index)) 1): else if (carry-bit + (value of operand-1(index)) + (value of operand-2 [index)-#2): else: I/ a sum of 3 means write down a 1 and carry the other 1 if (carry-bit)// Deal with any leftover carry bit sum a "1" sum return sum 3. Now it's time to tackle the problem of negative numbers in binary. Clearly, computers must be able to handle negative integers; otherwise, we could never execute an instruction like Stony Brook University

Explanation / Answer

The following is the complete implementation of the addBinary method.

public static String addBinary(String binary1, String binary2)
   {
       int carry_bit = 0;
       String sum = "";

       if (binary1.length() < binary2.length())
       {
           binary1 = pad(binary1, binary2.length());
}
       else if (binary1.length() > binary2.length())
       {
           binary2 = pad(binary2, binary1.length());
}
       char[] string1 = binary1.toCharArray();
       char[] string2 = binary2.toCharArray();

       for (int i = (string1.length - 1); i >= 0; i--)
       {
           if ((carry_bit + Character.getNumericValue(string1[i]) + Character.getNumericValue(string2[i])) == 0)
           {
               sum = "0" + sum ;
               carry_bit = 0;
           }
           else if ((carry_bit + Character.getNumericValue(string1[i]) + Character.getNumericValue(string2[i])) == 1)
           {
               sum = "1" + sum;
               carry_bit = 0;
           }
           else if ((carry_bit + Character.getNumericValue(string1[i]) + Character.getNumericValue(string2[i])) == 2)
           {
               sum = "0" + sum;
               carry_bit = 1;
           }
           else
           {
               sum = "1" + sum;
               carry_bit = 1;
           }

       }
       if (carry_bit == 1)
           sum = "1" + sum;

       return sum;
   }