diff options
| author | 冯昶 <seaker@qq.com> | 2020-09-28 17:13:38 +0800 |
|---|---|---|
| committer | 冯昶 <seaker@qq.com> | 2020-09-28 17:13:38 +0800 |
| commit | 77ff55eb1341ab51717bc619629cf3a39f799e50 (patch) | |
| tree | 74b23f13e52303d22fa58ee592c45002e274abb8 /challenge-079/bob-lied/perl/lib/CountSetBit.pm | |
| parent | acbc30c04977af09ff3e93e74642e325ea1e7083 (diff) | |
| parent | aa14cbf8342e04b936f40bcc720a23a258137ecd (diff) | |
| download | perlweeklychallenge-club-77ff55eb1341ab51717bc619629cf3a39f799e50.tar.gz perlweeklychallenge-club-77ff55eb1341ab51717bc619629cf3a39f799e50.tar.bz2 perlweeklychallenge-club-77ff55eb1341ab51717bc619629cf3a39f799e50.zip | |
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'challenge-079/bob-lied/perl/lib/CountSetBit.pm')
| -rw-r--r-- | challenge-079/bob-lied/perl/lib/CountSetBit.pm | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/challenge-079/bob-lied/perl/lib/CountSetBit.pm b/challenge-079/bob-lied/perl/lib/CountSetBit.pm new file mode 100644 index 0000000000..1733d4e676 --- /dev/null +++ b/challenge-079/bob-lied/perl/lib/CountSetBit.pm @@ -0,0 +1,55 @@ +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# CountSetBit.pm +#============================================================================= +# Copyright (c) 2020, Bob Lied +#============================================================================= +# Description: +#============================================================================= + +package CountSetBit; + +use strict; +use warnings; +use v5.30; + +use feature qw/ signatures /; +no warnings qw/ experimental::signatures /; + +require Exporter; +our @ISA = qw(Exporter); +our @EXPORT = qw(); +our @EXPORT_OK = qw(); + +sub new($class, $n) +{ + $class = ref($class) || $class; + my $self = { + _n => $n, + + _sum => 0, + }; + bless $self, $class; + return $self; +} + +# https://www.techiedelight.com/brian-kernighans-algorithm-count-set-bits-integer/ +sub run($self) +{ + $self->{_sum} += $self->_bitsOf($_) for ( 1 .. $self->{_n} ); + return ( $self->{_sum} % 1000000007 ); +} + +sub _bitsOf($self, $n)a +{ + my $count = 0; + + while ( $n > 0 ) + { + $count++; + $n = $n & ($n-1); + } + return $count; +} + +1; |
