Coding Quiz: Binary Addition
Another common question is:
Write a program to add two binary numbers without the use of the + operator.
Questions to Ask:
Are the numbers of arbitrary length or size? If the numbers are of identical length; then the processing is significantly easier. I think this answer depends on what they are truly interested in seeing as well as how much time you are given to solve the problem.
Are there any other operators that can not be used? As pointed out by others; one can use the - operator to do this. You may get a pat on the back for an out of the box method.
Solution: There are two distinct areas that you will need to right code in. First thing to realize is that this problem can be solved by recursion. Consider the lowest digits first then work your way up.
How to add two single digit binary numbers: there are only three possible outcomes depending on the values of the numbers ( either 0 or 1):
0 and 0 : The result for this is always 0 with a carry of 0
0 and 1 ( or 1 and 0): The result for this is always 1 with a carry of 0
1 and 1: the result for this is 0 with a carry value of 1
What is a carry ?: When I talk about carry value I am referring to result of a calculation that requires an extra number to handle. This value needs to get passed along to the next calc. For example; if the test values were 1 and 1; we would report the result as 10 (that is 2 which is a 1 in the second digit) since there are no additional digits to take into account. So the idea here is to use this same procedure to each of the digits in the numbers.
How to end the recursion?:
So now we need to think: how do we end it? We have checks put in such that when it detects "0b" as one of the remaining numbers that it does the following:
If both numbers are now "0b": Then we can end the process. We need to be careful though and check to seei f there is a remaining carry and to prepend that to the result.
If either number is now "0b": If we have a non-zero carry; we append it onto the number that is currently "0b" and we repeat the process with one final call; also making sure to set the carry value to zero. If there is no carry value; then we just prepend the remaining number to the result.
How to represent binary numbers?: It made the most sense to me to consider both binary numbers as strings. I found it particularly useful since I was able to use various slice operations to streamline the solution.
Here is the code that is checked into Github
https://gist.github.com/6576421






