From bde6bd6403b1d25a37db6133cbb90a47699884c3 Mon Sep 17 00:00:00 2001 From: Niels van Dijke Date: Mon, 21 Nov 2022 09:04:24 +0000 Subject: w192 - Task 1 --- challenge-192/perlboy1967/perl/ch-1.pl | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100755 challenge-192/perlboy1967/perl/ch-1.pl 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)}, +}); -- cgit