Skip to content

Instantly share code, notes, and snippets.

@vkuznetsov
Created April 8, 2021 07:50
Show Gist options
  • Save vkuznetsov/7e8a36ec23fbbabde8491a679145d612 to your computer and use it in GitHub Desktop.
Save vkuznetsov/7e8a36ec23fbbabde8491a679145d612 to your computer and use it in GitHub Desktop.
listsum
-module(listsum).
-export([add_two_numbers/2]).
add_two_numbers(L1, L2) ->
lists:reverse(add_two_lists(L1, L2, 0, [])).
add_two_lists([], [], 0, Acc) ->
Acc;
add_two_lists([], [], Over, Acc) ->
[Over|Acc];
add_two_lists([] = L1, [V2|L2], Over, Acc) ->
next_step(L1, L2, V2 + Over, Acc);
add_two_lists([V1|L1], [] = L2, Over, Acc) ->
next_step(L1, L2, V1 + Over, Acc);
add_two_lists([V1|L1], [V2|L2], Over, Acc) ->
next_step(L1, L2, V1 + V2 + Over, Acc).
next_step(L1, L2, Sum, Acc) when Sum >= 10 ->
add_two_lists(L1, L2, 1, [Sum - 10 | Acc]);
next_step(L1, L2, Sum, Acc) ->
add_two_lists(L1, L2, 0, [Sum | Acc]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment