aboutsummaryrefslogtreecommitdiff
path: root/challenge-120
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2021-07-11 09:18:23 +0100
committerGitHub <noreply@github.com>2021-07-11 09:18:23 +0100
commit8b9e33d777a714eaef55168fdcb0217bfb9b7668 (patch)
treedee622920a5c1f8e06353a0b2d2d968c49c4bde8 /challenge-120
parent091011ae56b19db7de27d84018d2c1cb015e3b4e (diff)
parent22a6c7204e9913e63f02d50515c121b8c20226cd (diff)
downloadperlweeklychallenge-club-8b9e33d777a714eaef55168fdcb0217bfb9b7668.tar.gz
perlweeklychallenge-club-8b9e33d777a714eaef55168fdcb0217bfb9b7668.tar.bz2
perlweeklychallenge-club-8b9e33d777a714eaef55168fdcb0217bfb9b7668.zip
Merge pull request #4480 from corvettes13/patch-1
Create ch-1.pl
Diffstat (limited to 'challenge-120')
-rw-r--r--challenge-120/paul-fajman/perl/ch-1.pl42
1 files changed, 42 insertions, 0 deletions
diff --git a/challenge-120/paul-fajman/perl/ch-1.pl b/challenge-120/paul-fajman/perl/ch-1.pl
new file mode 100644
index 0000000000..df7a0e0135
--- /dev/null
+++ b/challenge-120/paul-fajman/perl/ch-1.pl
@@ -0,0 +1,42 @@
+#!/usr/bin/perl
+
+# Weekly Challenge 120 Task #1
+# 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.
+
+use strict;
+use warnings;
+
+my $number = $ARGV[0];
+my $binary = sprintf ('%b', $number);
+my ($out1, $out2);
+my $final;
+
+# Determine if we have odd or even amount of binary digits
+if (length($binary) % 2) {
+ $binary = "0".$binary # Odd so add leading 0.
+}
+
+my @binary = split(//,$binary);
+my $i;
+my $new;
+
+# Loop over the binary number to perform swap
+for ($i=0; $i<$#binary+1; $i+=2) {
+ $out1.= $binary[$i].$binary[$i+1]." ";
+ $out2.= $binary[$i+1].$binary[$i]." ";
+ $new.="$binary[$i+1]"."$binary[$i]";
+}
+
+$final = eval("0b".$new); # Convert back to decimal number
+chomp($out1);
+chomp($out2);
+
+print "Input: \$N = $number\n";
+print "Output: $final\n\n";
+
+print "Binary representation of the given number is $out1\n";
+print "The new binary representation after the odd/even swap is $out2\n";
+print "The decimal equivalent of $new is $final\n";
+