Carrying on from Cedric’s Challenge (C#, Erlang) I decided to do some of the Programming Challenges problems in Erlang, because the problems are small, but fun.
My first is Reverse And Add #110502 and here is my solution:
-module(revandadd).
-export([rev_and_add/1, test/0]).%% number to list
ntl(Num) ->
ntl(Num, []).
ntl(0, List) ->
List;
ntl(Num, List) ->
ntl(Num div 10, [Num rem 10]++List).
%% list to number
ltn(List) ->
ltn(List, 0).
ltn([], Num) ->
Num;
ltn([H|T], Num) ->
ltn(T, (Num*10)+H).
%% is palindrome
is_pal(Num) ->
ntl(Num) == lists:reverse(ntl(Num)).
rev_and_add(Num) ->
rev_and_add(Num, 1).
rev_and_add(Num, Count) ->
Pal = ltn(lists:reverse(ntl(Num))) + Num,
case is_pal(Pal) of
true ->
[Count,Pal];
false ->
rev_and_add(Pal, Count+1)
end.
test() ->
[4,9339] = rev_and_add(195),
[5,45254] = rev_and_add(265),
[3,6666] = rev_and_add(750),
true.
I’m not too happy with the number-to-list functions as I’m sure there should be a built in way to-do this already, which Joe implies therefore there probably is.