diff options
| author | Niels van Dijke <perlboy@cpan.org> | 2022-11-21 09:04:24 +0000 |
|---|---|---|
| committer | Niels van Dijke <perlboy@cpan.org> | 2022-11-21 09:04:24 +0000 |
| commit | bde6bd6403b1d25a37db6133cbb90a47699884c3 (patch) | |
| tree | 679fd22c65bdd0b35c33bd906aa03563511d394a | |
| parent | 8ea75399a70f8ab625f105a9d5ca011759e9dc19 (diff) | |
| download | perlweeklychallenge-club-bde6bd6403b1d25a37db6133cbb90a47699884c3.tar.gz perlweeklychallenge-club-bde6bd6403b1d25a37db6133cbb90a47699884c3.tar.bz2 perlweeklychallenge-club-bde6bd6403b1d25a37db6133cbb90a47699884c3.zip | |
w192 - Task 1
| -rwxr-xr-x | challenge-192/perlboy1967/perl/ch-1.pl | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/challenge-192/perlboy1967/perl/ch-1.pl b/challenge-192/perlboy1967/perl/ch-1.pl new file mode 100755 index 0000000000..106fed0019 --- /dev/null +++ b/challenge-192/perlboy1967/perl/ch-1.pl @@ -0,0 +1,59 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 192 + - https://theweeklychallenge.org/blog/perl-weekly-challenge-192/#TASK1 + +Author: Niels 'PerlBoy' van Dijke + +Task 1: Binary Flip +Submitted by: Mohammad S Anwar + +You are given a positive integer, $n. + +Write a script to find the binary flip. + +=cut + +use v5.16; +use warnings; + +use Test::More; +use Benchmark qw(:all); + + +sub binaryFlipString ($) { + my $n = sprintf('%b',$_[0]); + $n =~ tr/01/10/; + return oct('0b'.$n); +} + +sub binaryFlipBinary ($) { + my ($i,$m) = ($_[0],0); + # Create bitmask for 'AND' below + while ($i) { + $i >>= 1; $m = ($m << 1) + 1; + } + return ~$_[0] & $m; +} + + +is(binaryFlipString(5),2); +is(binaryFlipString(5),2); +is(binaryFlipString(4),3); +is(binaryFlipString(6),1); +is(binaryFlipString(0b10101),0b1010); + +is(binaryFlipBinary(5),2); +is(binaryFlipBinary(5),2); +is(binaryFlipBinary(4),3); +is(binaryFlipBinary(6),1); +is(binaryFlipBinary(0b10101),0b1010); + +done_testing; + +cmpthese(1_000_000, { + 'Binary' => sub{binaryFlipBinary(12345678)}, + 'String' => sub{binaryFlipString(12345678)}, +}); |
