Skip to content

Instantly share code, notes, and snippets.

@fswalker
Created March 4, 2017 22:41
Show Gist options
  • Save fswalker/3be48b64ce8ace8e3b1bb289d060104c to your computer and use it in GitHub Desktop.
Save fswalker/3be48b64ce8ace8e3b1bb289d060104c to your computer and use it in GitHub Desktop.
-module(ex1_bits).
-export([bits_direct/1,test_bits_direct/0,bits_tail/2,test_bits_tail/0,run_tests/0]).
bits_direct(0) ->
0;
bits_direct(N) ->
N rem 2 + bits_direct(N div 2).
bits_tail(0, B) ->
B;
bits_tail(N, B) ->
bits_tail(N div 2, N rem 2 + B).
% Tests
test_bits_direct() ->
D = [0,1,2,3,4,5,6,7,8,9,10,255,2047,14323],
A = lists:map(fun(X) -> bits_direct(X) end, D),
A = [0,1,1,2,1,2,2,3,1,2,2,8,11,11],
'Tests passed'.
test_bits_tail() ->
D = [0,1,2,3,4,5,6,7,8,9,10,255,2047,14323],
A = lists:map(fun(X) -> bits_tail(X, 0) end, D),
A = [0,1,1,2,1,2,2,3,1,2,2,8,11,11],
'Tests passed'.
run_tests() ->
test_bits_direct(),
test_bits_tail(),
'All tests passed'.
@fswalker
Copy link
Author

fswalker commented Mar 4, 2017

You need Erlang installed on your machine.

  1. Save this gist in some folder

  2. Open erl in command line in that folder

  3. Compile the file: c(ex1_bits).

  4. Run tests: ex1_bits:run_tests().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment