RabbitFarm

2020-11-01

Perl Weekly Challenge 084

Part 1

You are given an integer $N. Write a script to reverse the given integer and print the result. Print 0 if the result doesn’t fit in 32-bit signed integer.

Solution


use strict;
use warnings;
##
# You are given an integer $N.
# Write a script to reverse the given integer and print the result. 
# Print 0 if the result doesn’t fit in 32-bit signed integer.
##
use Config;
use boolean;
use constant MAX_32BIT_SIGNED => 2_147_483_647;

sub reverse_digits{
    my($n) = @_;
    return 0 if $n > MAX_32BIT_SIGNED || $n < -1*MAX_32BIT_SIGNED;
    my $negative = $n < 0 ? true : false;
    $n = abs($n) if $negative;
    return join("", reverse split(//, $n)) if !$negative;
    return "-" . join("", reverse split(//, $n));
}

MAIN:{
    my $A = $ARGV[0];
    print reverse_digits($A) . "\n";   
}

Sample Run


$ perl perl/ch-1.pl -123452
-254321
$ perl perl/ch-1.pl 12345
54321
$ perl perl/ch-1.pl -2147483647
-7463847412
$ perl perl/ch-1.pl -2147483648
0
$ perl perl/ch-1.pl 2147483647
7463847412
$ perl perl/ch-1.pl 2147483
3847412

Notes

Before starting this I did a little research and found some interesting articles. This Perlmonks thread covers the topic on the size in bytes of integers in Perl. This thread gets into how to detect overflow. In this challenge, however, we don’t need to really know any of this since the perl I am using (5.28.0) on my Mac Mini (running OS X) can easily accomodate much larger numbers than the 32-bit signed restriction placed here. All that need be done is check to see if the number is above or below this maximum/minimum.

posted at: 14:57 by: Adam Russell | path: /perl | permanent link to this entry