From 3dee9de223167c959c3edca316a4e8476dcf8d7d Mon Sep 17 00:00:00 2001 From: Cris-HD Date: Thu, 24 Sep 2020 12:47:33 +0200 Subject: added ch-1.pl --- challenge-079/cristian-heredia/perl/ch-1.pl | 59 +++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100755 challenge-079/cristian-heredia/perl/ch-1.pl (limited to 'challenge-079') 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++; + } + } +} + + + + -- cgit