"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: Sum of Two Integers.\n",
"\n",
"See the [LeetCode](https://leetcode.com/problems/sum-of-two-integers/) problem page.\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 we're working with 32 bit ints?\n",
" * Yes\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",
"* 5, 7 -> 12\n",
"* -5, -7 -> -12\n",
"* 5, -7 -> -2\n",
"</pre>"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Algorithm\n",
"\n",
"We'll look at the following example, adding a and b:\n",
"\n",
"<pre>\n",
"a 0111 \n",
"b 0101\n",
"</pre>\n",
"\n",
"First, add a and b, without worrying about the carry (0+0=0, 0+1=1, 1+1=0):\n",
"\n",
"result = a ^ b = 0010\n",
"\n",
"Next, calculate the carry (1+1=2). We'll need to left shift one to prepare for the next iteration when we move to the next most significant bit:\n",