QUESTION

Text
Image

please use carry bits


2. Write a function called add_bitwise(b1, b2) that adds two binary numbers. This function must $\boldsymbol{u} \boldsymbol{s e}$ recursion to perform the bitwise, "elementary-school" addition algorithm that we discussed in lecture, and it should return the result. It must not perform any base conversions, and it must not call the add function from Problem 2. Your function should add one pair of bits at a time, working from right to left and including any necessary "carry" bits, as discussed in lecture. For example, when adding 101110 and 100111, you end up with 3 carry bits, as shown in blue below: \[ \begin{array}{c} 111 \\ 101110 \\ +\quad 100111 \\ \hline 1010101 \end{array} \] Notes/hints: - Base cases: Because the function will be called recursively on smaller and smaller strings, you will eventually get down to an empty string for one or both of the inputs. If either of the strings (b1 or b2) is the empty string, your function should return the other string. - Handling cases that require a carry bit can be the most difficult part of this problem. The trick is to call the function recursively a second time to add in the carry bit! We discussed this in Monday's lecture. - Here are some test cases: >> add_bitwise('11', '100') result: '111' >> add_bitwise('11', '1') resu7t: '100' >> add_bitwise(', '101') result: '101' >> add_bitwise('11100', '11110') result: '111010' $>$ add_bitwise('11', '100') result: '111' $\gg$ add_bitwise('11', '1') result: '100' $\gg$ add_bitwise(' , '101') result: '101' $>$ add_bitwise ('11100', '11110') resu7t: '111010' Make sure to try other test cases to ensure that your function works correctly in all cases!

Public Answer

ASHFE3 The First Answerer