"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: Given an int, repeatedly add its digits until the result is one digit.\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 num is not negative?\n",
" * Yes\n",
"* Can we assume the inputs are valid?\n",
" * No\n",
"* Can we assume this fits memory?\n",
" * Yes"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Test Cases\n",
"\n",
"<pre>\n",
"* None input -> TypeError\n",
"* negative input -> ValueError\n",
"* 9 -> 9\n",
"* 138 -> 3\n",
"* 65536 -> 7\n",
"</pre>"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Algorithm\n",
"\n",
"The naive solution simply isolates each digit with with modulo and integer division. We'll add each isolated digit to a list and sum the values.\n",
"\n",
"<pre>\n",
"138 % 10 = 8 -> isolated\n",
"138 // 10 = 13\n",
"13 % 10 = 3 -> isolated\n",
"13 // 10 = 1\n",
"1 % 10 = 1 -> isolated\n",
"</pre>\n",
"\n",
"A more optimal solution exists, by recognizing this is a digital root. See the [Wikipedia article](https://en.wikipedia.org/wiki/Digital_root) for more information.\n",