diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-11-21 13:21:28 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-11-21 13:21:28 +0000 |
| commit | 0c88577ef9852fce77a47fad1d42e2f174b069e3 (patch) | |
| tree | 4af24df2117b2c1d5e195ea6ec99fd7de5a56574 | |
| parent | 5861cd22a45a47534f247d5f75a326e9bace7d04 (diff) | |
| parent | 304dabde4db121ff97d6090e537b96d892d51294 (diff) | |
| download | perlweeklychallenge-club-0c88577ef9852fce77a47fad1d42e2f174b069e3.tar.gz perlweeklychallenge-club-0c88577ef9852fce77a47fad1d42e2f174b069e3.tar.bz2 perlweeklychallenge-club-0c88577ef9852fce77a47fad1d42e2f174b069e3.zip | |
Merge pull request #7127 from PerlBoy1967/branch-for-challenge-192
w192 - Task 1
| -rwxr-xr-x | challenge-192/perlboy1967/perl/ch-1.pl | 84 |
1 files changed, 84 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..fb4e36b839 --- /dev/null +++ b/challenge-192/perlboy1967/perl/ch-1.pl @@ -0,0 +1,84 @@ +#!/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); +use Inline 'C'; + + +sub binaryFlipString ($) { + return oct('0b'.sprintf('%b',$_[0]) =~ tr/01/10/r); +} + +sub binaryFlipBinary ($) { + my ($i,$m) = ($_[0],0); + + # Create bitmask for 'AND' in 'return' + while ($i) { + $i >>= 1; + $m <<= 1; + $m++; + } + + 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); + +is(binaryFlipC(5),2); +is(binaryFlipC(5),2); +is(binaryFlipC(4),3); +is(binaryFlipC(6),1); +is(binaryFlipC(0b10101),0b1010); +done_testing; + +cmpthese(5_000_000, { + 'Binary' => sub{binaryFlipBinary(12345678)}, + 'BinaryC' => sub{binaryFlipC(12345678)}, + 'String' => sub{binaryFlipString(12345678)}, +}); + +__END__ +__C__ + +int binaryFlipC (int i) { + int j = i; + int m = 0; + + while (j) { + j >>= 1; + m <<= 1; + m++; + } + + return ~i & m; +} |
