RabbitFarm
2021-05-30
The Weekly Challenge 114
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given a positive integer $N. Write a script to find out the next Palindrome Number higher than the given integer $N.
Solution
use strict;
use warnings;
sub next_palindrome{
my($n) = @_;
{
$n++;
return $n if $n eq join("", reverse(split(//, $n)));
redo;
}
}
MAIN:{
my($N);
$N = 1234;
print next_palindrome($N) . "\n";
$N = 999;
print next_palindrome($N) . "\n";
}
Sample Run
$ perl perl/ch-1.pl
1331
1001
Notes
This is probably the most straight forward approach to this task. Here we iterate upwards from our starting point and check each number using reverse. Since we are guaranteed of eventually finding a palindrome the loop is done (via redo) without any exit criteria or bounds checking other than returning when one is found.
Part 2
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.
Solution
use strict;
use warnings;
sub count_bits{
my($n) = @_;
my $total_count_set_bit = 0;
while($n){
my $b = $n & 1;
$total_count_set_bit++ if $b;
$n = $n >> 1;
}
return $total_count_set_bit;
}
sub next_same_bits{
my($n) = @_;
my $number_bits = count_bits($n);
{
my $next = $n + 1;
return $next if count_bits($next) == $number_bits;
$n = $next;
redo;
}
}
MAIN:{
my($N);
$N = 3;
print next_same_bits($N) . "\n";
$N = 12;
print next_same_bits($N) . "\n";
}
Sample Run
$ perl perl/ch-2.pl
5
17
Notes
The count_bits
subroutine is based on code written for
Challenge 079. Otherwise, the approach
to this task is very similar to what was done in the first one this week.
References
posted at: 16:01 by: Adam Russell | path: /perl | permanent link to this entry