aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2021-11-28 16:05:18 +0000
committerGitHub <noreply@github.com>2021-11-28 16:05:18 +0000
commit223e0a601acaaa5484194c2de586339d6aa36ff8 (patch)
treea4353de4a256aee6629ca1169e7049eae49ea02e
parent74b6e49f8932f633d206f5f3d82c4785b52d23b3 (diff)
parent56f364b119b68cb8c0efba61601fe17162659b3f (diff)
downloadperlweeklychallenge-club-223e0a601acaaa5484194c2de586339d6aa36ff8.tar.gz
perlweeklychallenge-club-223e0a601acaaa5484194c2de586339d6aa36ff8.tar.bz2
perlweeklychallenge-club-223e0a601acaaa5484194c2de586339d6aa36ff8.zip
Merge pull request #5293 from mano6616/new-branch
Solutions for challenge 140 Task1
-rw-r--r--challenge-140/mano-chandar/perl/ch-1.pl45
1 files changed, 45 insertions, 0 deletions
diff --git a/challenge-140/mano-chandar/perl/ch-1.pl b/challenge-140/mano-chandar/perl/ch-1.pl
new file mode 100644
index 0000000000..ea9772f07f
--- /dev/null
+++ b/challenge-140/mano-chandar/perl/ch-1.pl
@@ -0,0 +1,45 @@
+## user input should be binary numbers(1,0)
+## Find the lenght of two input numbers and traverse from LSB
+## ## intially carry =0
+## sum = carry+ n1+n2;
+## when we add the numbers sum possiblity is {3,2,0,1} then set the carry if sum is greater than 1; if we use modulse we can find the actuall result of sum
+## if sum is 3 -> 1(actual result)
+## if sum is 2 -> 0
+## if sum is 1 -> 1
+## if sum is 0 -> 0
+
+
+use strict;
+use warnings;
+
+
+my($input1,$input2,$i,$j,$result,$carry,$sum);
+$carry = 0; $sum =0, $result='';
+
+L1 : print "Enter the First Binary Number [0's and 1's only]\n";
+ $input1 = <>;
+ chomp($input1);
+ goto L1 if ($input1 !~ m/^[0-1]+$/s);
+L2 : print "Enter the Second Binary Number [0's and 1's only]\n";
+ $input2 = <>;
+ chomp($input2);
+ goto L2 if ($input2 !~ m/^[0-1]+$/s);
+
+chomp $input1; chomp $input2;
+
+$i = length($input1);
+$j = length($input2);
+
+while( $i>0 || $j>0)
+{
+ $sum = $carry;
+ $sum += (substr($input1, $i-1, 1)) if ($i >0); # operator overloading
+ $sum += (substr($input2, $j-1, 1)) if ($j >0); # operator overloading
+ $carry = $sum > 1 ? 1 : 0 ;
+ $result .= $sum%2; # operator overloading
+ $i--; $j--;
+}
+$result .= $carry if ($carry);
+
+print (scalar reverse($result));
+