Last active
March 21, 2017 13:42
-
-
Save mcelaney/28cd90b547e4b2d20ecdadbc3c770462 to your computer and use it in GitHub Desktop.
March 21, 2017 PhillyDevSlack #Daily_Programmer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule SumJawn do | |
@moduledoc """ | |
As any number greater than 9 is represented by several digits, we can | |
calculate the sum of these digits. For example, for numbers 1492 and 1776 | |
we get: | |
```1 + 4 + 9 + 2 = 16 | |
1 + 7 + 7 + 6 = 21 | |
``` | |
In this task you will be given several numbers and asked to calculate their | |
sums of digits. | |
Many programming languages have built-in functions to convert numbers to | |
strings (from which digits could be extracted), you should totally use this | |
(since your goal is to learn some programming tricks). But it's also helpful | |
to try to implement algorithm with repetitive division by 10 (base of | |
numeral system) and summing up the remainders. | |
Please DM me with ideas for future problems. When you have completed it post a | |
link to your solution. | |
""" | |
@doc """ | |
## Example | |
iex> SumJawn.sumit(0) | |
0 | |
iex> SumJawn.sumit(6) | |
6 | |
iex> SumJawn.sumit(1492) | |
16 | |
iex> SumJawn.sumit(1776) | |
21 | |
iex> SumJawn.sumit(-1776) | |
21 | |
""" | |
@spec sumit(integer) :: non_neg_integer | |
def sumit(number) when number < 0, do: number |> abs |> sumit | |
def sumit(number), do: sumit(0, number) | |
@spec sumit(non_neg_integer, non_neg_integer) :: non_neg_integer | |
defp sumit(acc, 0), do: acc | |
defp sumit(acc, number) do | |
number | |
|> Integer.mod(10) | |
|> Kernel.+(acc) | |
|> sumit(Integer.floor_div(number, 10)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment