diff options
| -rwxr-xr-x | challenge-192/tim-potapov/perl/ch-1.pl | 65 |
1 files changed, 38 insertions, 27 deletions
diff --git a/challenge-192/tim-potapov/perl/ch-1.pl b/challenge-192/tim-potapov/perl/ch-1.pl index a626d6d3bd..0c0dfb96c5 100755 --- a/challenge-192/tim-potapov/perl/ch-1.pl +++ b/challenge-192/tim-potapov/perl/ch-1.pl @@ -11,45 +11,56 @@ You are given a positive integer, $n. Write a script to find the binary flip. -Example 1 -Input: $n = 5 -Output: 2 - -First find the binary equivalent of the given integer, 101. -Then flip the binary digits 0 -> 1 and 1 -> 0 and we get 010. -So Binary 010 => Decimal 2. -Example 2 -Input: $n = 4 -Output: 3 - -Decimal 4 = Binary 100 -Flip 0 -> 1 and 1 -> 0, we get 011. -Binary 011 = Decimal 3 -Example 3 -Input: $n = 6 -Output: 1 - -Decimal 6 = Binary 110 -Flip 0 -> 1 and 1 -> 0, we get 001. -Binary 001 = Decimal 1 - =cut -sub function { - my ( $input ) = @_; +sub binary_flip { + my ( $decimal ) = @_; + my $len = length sprintf "%b", $decimal; + my $biggest_binary = oct( "b" . ( 1 x $len ) ); + + $biggest_binary & ~$decimal; + # Orinally thought to just do this, + # but couldn't figure out how to + # get the max allowed soze: 0x7: + # 0x7 & ~$decimal; } my @cases = ( { - Name => 'Example1', - Input => 1, + Name => 'Example 1', + Input => 5, + Output => 2, + }, + { + Name => 'Example 2', + Input => 4, + Output => 3, + }, + { + Name => 'Example 3', + Input => 6, Output => 1, }, + { + Name => 'Example 4', + Input => 10, + Output => 5, + }, + { + Name => 'Example 5', + Input => 14, + Output => 1, + }, + { + Name => 'Example 6', + Input => 35, + Output => 28, + }, ); for ( @cases ) { - is function( $_->{Input} ), $_->{Output}, "$_->{Name} - $_->{Input}"; + is binary_flip( $_->{Input} ), $_->{Output}, "$_->{Name} - $_->{Input}"; } done_testing(); |
