"This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges)."
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"# Solution Notebook"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Problem: Find the difference of two integers without using the + or - sign.\n",
"\n",
"* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n",
"* [Algorithm](#Algorithm)\n",
"* [Code](#Code)\n",
"* [Unit Test](#Unit-Test)"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Constraints\n",
"\n",
"* Can we assume the inputs are valid?\n",
" * No, check for None\n",
"* Can we assume this fits memory?\n",
" * Yes"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Test Cases\n",
"\n",
"<pre>\n",
"* None input -> TypeError\n",
"* 7, 5 -> 2\n",
"* -5, -7 -> 2\n",
"* -5, 7 -> -12\n",
"* 5, -7 -> 12\n",
"</pre>"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Algorithm\n",
"\n",
"We'll look at the following example, subtracting a and b:\n",
"\n",
"<pre>\n",
"a 0110 = 6 \n",
"b 0101 = 5\n",
"</pre>\n",
"\n",
"First, subtract a and b, without worrying about the borrow (0-0=0, 0-1=1, 1-1=0):\n",
"\n",
"result = a ^ b = 0011\n",
"\n",
"Next, calculate the borrow (0-1=1). We'll need to left shift one to prepare for the next iteration when we move to the next most significant bit:\n",