diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2021-07-11 17:57:37 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-07-11 17:57:37 +0100 |
| commit | b6ae21ba769b910c5ce747aaf9e81fd86fd1ec12 (patch) | |
| tree | 35d0f18dd6ffb65663627f47472e85b8403a150b /challenge-120 | |
| parent | c5b6045dd780f65174f9eecae20162b6fc68e72a (diff) | |
| parent | 5b553b685102eccfed7a5165f2b1d64ce242a98d (diff) | |
| download | perlweeklychallenge-club-b6ae21ba769b910c5ce747aaf9e81fd86fd1ec12.tar.gz perlweeklychallenge-club-b6ae21ba769b910c5ce747aaf9e81fd86fd1ec12.tar.bz2 perlweeklychallenge-club-b6ae21ba769b910c5ce747aaf9e81fd86fd1ec12.zip | |
Merge pull request #4485 from Cris-HD/branch-for-challenge-120
Added challenge 120 solution
Diffstat (limited to 'challenge-120')
| -rwxr-xr-x | challenge-120/cristian-heredia/perl/ch_1.pl | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/challenge-120/cristian-heredia/perl/ch_1.pl b/challenge-120/cristian-heredia/perl/ch_1.pl new file mode 100755 index 0000000000..5674d9a23c --- /dev/null +++ b/challenge-120/cristian-heredia/perl/ch_1.pl @@ -0,0 +1,57 @@ +=begin + TASK #1 › Swap Odd/Even bits + Submitted by: Mohammad S Anwar + You are given a positive integer $N less than or equal to 255. + + Write a script to swap the odd positioned bit with even positioned bit and print the decimal equivalent of the new binary representation. + + Example + Input: $N = 101 + Output: 154 + + Binary representation of the given number is 01 10 01 01. + The new binary representation after the odd/even swap is 10 01 10 10. + The decimal equivalent of 10011010 is 154. + + Input: $N = 18 + Output: 33 + + Binary representation of the given number is 00 01 00 10. + The new binary representation after the odd/even swap is 00 10 00 01. + The decimal equivalent of 100001 is 33. + +=end +=cut + +use warnings; +use strict; +use Data::Dumper; + +my $N = 101; +my @bits; +my $newNumber = ''; + +splitBinary(); + + +sub splitBinary { + @bits = split(//, sprintf ("%b", $N)); + if (@bits % 2 != 0){ + unshift @bits, '0'; + } + swapNumbers(); +} + +sub swapNumbers { + foreach(my $i=0;$i<@bits;$i+=2){ + $newNumber = $newNumber.$bits[$i+1].$bits[$i]; + } + convertDecimal(); +} + +sub convertDecimal { + my $result = eval("0b$newNumber"); + print("Output: $result"); +} + + |
