diff options
| author | David Schwartz <dms061@bucknell.edu> | 2021-05-26 02:50:45 -0400 |
|---|---|---|
| committer | David Schwartz <dms061@bucknell.edu> | 2021-05-26 02:50:45 -0400 |
| commit | c08580641fea92c9ac4c980442931ee7af585eee (patch) | |
| tree | fb303557ef79ab8e1788521ed6de0b63c283c63b | |
| parent | cde73d5be4fda5a32f973fbe0f3f6ba74d1fa35e (diff) | |
| download | perlweeklychallenge-club-c08580641fea92c9ac4c980442931ee7af585eee.tar.gz perlweeklychallenge-club-c08580641fea92c9ac4c980442931ee7af585eee.tar.bz2 perlweeklychallenge-club-c08580641fea92c9ac4c980442931ee7af585eee.zip | |
Added solutions for challenge114
| -rw-r--r-- | challenge-114/dms061/perl/ch-1.pl | 24 | ||||
| -rw-r--r-- | challenge-114/dms061/perl/ch-2.pl | 35 |
2 files changed, 59 insertions, 0 deletions
diff --git a/challenge-114/dms061/perl/ch-1.pl b/challenge-114/dms061/perl/ch-1.pl new file mode 100644 index 0000000000..89aaf72343 --- /dev/null +++ b/challenge-114/dms061/perl/ch-1.pl @@ -0,0 +1,24 @@ +=pod + +=head1 Question 1: + +Next Palindrome Number +You are given a positive integer $N +Write a script to find out the next Palindrome Number higher than the given integer $N + +=head1 Approach + +Going to keep this one simple, increase $N until it becomes a palidrome. + +=cut + +use strict; +use warnings; + +die "Need to supply a positive integer (as a command line argument)!\n" if @ARGV == 0; +my $n = shift; +die "Input must be positive\n" if $n < 1; + +# Increase n until we have a new palindrome +do { ++$n; } until $n eq reverse $n; +print "$n\n"; diff --git a/challenge-114/dms061/perl/ch-2.pl b/challenge-114/dms061/perl/ch-2.pl new file mode 100644 index 0000000000..42b98003a1 --- /dev/null +++ b/challenge-114/dms061/perl/ch-2.pl @@ -0,0 +1,35 @@ +=pod + +=head1 Question 2 + +Higher Integer Set Bits +You are given a positive integer $N. +Write a script to find the next higher integer having the same number of 1 bits in binary representation as $N + +=head1 Approach + +Also starting with a simple approach. Count 1s in bitstring of $N and increase $N until +we have another bitstring with the same number of 1s + +Should check on this approach again later to exploit the properties of binary representation to determine +an easier way than iterating through + +=cut + +sub count_ones { + my $n = shift; + # sprintf "%b, $n" creates a bitstring for $n and + # tr/1// counts the number of 1s in the string + return sprintf("%b", $n) =~ tr/1//; +} + +die "Need to enter a positive integer!\n" if @ARGV == 0; + +my $n = shift; +die "Integer needs to be positive!\n" if $n < 1; + +my $count = count_ones $n; +# Iterate until we have a match +do { ++$n; } until count_ones ($n) == $count; +print "$n\n"; + |
