fork download
  1. #!/usr/bin/perl
  2. use 5.016;
  3. use warnings;
  4. no warnings qw(once);
  5. use List::Util qw(reduce);
  6. use POSIX qw(ceil);
  7.  
  8. sub lb { log(shift) / log(2) }
  9.  
  10. sub f {
  11. my ($n, $l) = @_;
  12.  
  13. if (ref $n){
  14. my $x = reduce{ $a * 2 + $b } @{$n};
  15. return ($_[0]->[0] ? $x - (2 ** @{$n}) : $x);
  16. }
  17.  
  18. my @l = sub {
  19. $_[0] < 1 ? @{$_[1]} : __SUB__->(int($_[0] / 2), [$_[0] % 2, @{$_[1]}])
  20. }->(($n < 0 ? $n + 2 ** ceil(lb(abs $n) + 1) : $n), []);
  21.  
  22. return sub {
  23. ($_[0]) x (defined $l ? $l - @l : $_[1]), @l
  24. }->($n < 0 ? (1, 0) : (0, 1));
  25. }
  26.  
  27. say f(0);
  28. say f(1);
  29. say f(-1);
  30. say f(3);
  31. say f(-3);
  32. say f(10);
  33. say f(10, 8);
  34. say f(-8);
  35. say f(-8, 8);
  36.  
  37. say f([0]);
  38. say f([0, 1]);
  39. say f([1]);
  40. say f([0, 1, 1, 1]);
  41. say f([1, 1, 1, 1]);
  42. say f([1, 0, 0, 0]);
  43.  
Success #stdin #stdout 0.01s 4332KB
stdin
Standard input is empty
stdout
0
01
1
011
101
01010
00001010
1000
11111000
0
1
-1
7
-1
-8