diff options
| author | Cris-HD <crisn7@hotmail.com> | 2020-09-24 12:47:33 +0200 |
|---|---|---|
| committer | Cris-HD <crisn7@hotmail.com> | 2020-09-24 12:47:33 +0200 |
| commit | 3dee9de223167c959c3edca316a4e8476dcf8d7d (patch) | |
| tree | 735da07b11062399e15d4c5d02a0fde1100ece2d | |
| parent | 5ac16ac7e9826137e0da5597e954f4992c66205d (diff) | |
| download | perlweeklychallenge-club-3dee9de223167c959c3edca316a4e8476dcf8d7d.tar.gz perlweeklychallenge-club-3dee9de223167c959c3edca316a4e8476dcf8d7d.tar.bz2 perlweeklychallenge-club-3dee9de223167c959c3edca316a4e8476dcf8d7d.zip | |
added ch-1.pl
| -rwxr-xr-x | challenge-079/cristian-heredia/perl/ch-1.pl | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/challenge-079/cristian-heredia/perl/ch-1.pl b/challenge-079/cristian-heredia/perl/ch-1.pl new file mode 100755 index 0000000000..30e2136aa5 --- /dev/null +++ b/challenge-079/cristian-heredia/perl/ch-1.pl @@ -0,0 +1,59 @@ +#You are given a positive number $N. +#Write a script to count the total number of set bits of the binary representations of all numbers from 1 to $N and return $total_count_set_bit % 1000000007. + + #Input: $N = 3 + + #Explanation: First find out the set bit counts of all numbers i.e. 1, 2 and 3. + + # Decimal: 1 + # Binary: 01 + # Set Bit Count: 1 + + # Decimal: 2 + # Binary: 10 + # Set Bit Count: 1 + + # Decimal: 3 + # Binary: 11 + # Set Bit Count: 2 + + # Total set bit count: 1 + 1 + 2 = 4 + + #Output: Your script should print `4` as `4 % 1000000007 = 4`. + +use strict; +use warnings; +use Data::Dumper; + +#variables +my $N = 3; +my $bin; +my @array; +my $count = 0; + + +convertBinary(); +sub convertBinary { + + foreach(my $i = 1; $i <= $N; $i++) { + $bin = sprintf ("%b", $i); + @array = (); + @array = split //, $bin; + countBit(); + } + + print "output: $count\n"; +} + +sub countBit { + + foreach(my $j = 0; $j < @array; $j++) { + if ($array[$j] == 1) { + $count++; + } + } +} + + + + |
