Saturday, February 20, 2010

Perl recursion , decimal to binary

#!/usr/bin/perl

print &num2bin(10),"\n";


sub num2bin {
my $n = shift;
return $n if $n == 0 || $n == 1;

my $div = int($n / 2);
my $rem = $n % 2;
my $E = num2bin($div);

return $E . $rem;
}


the order of $E . $rem is very important.


Look at the code below. It prints in reverse. Not an elegant solution , incorrect solution rather. ohh its an infinite loop.

The above code has exit condition (base case) in the beginning and the one below has in the end.
The above code prints the bit in the code itself without using a return value.
order of $rem and $div also needs to be reversed.
The wrong code below highlights the importance of breaking down the problem into simpler sub units, and thats called recursion.

sub num2bin_reverse {
my $n = shift;

my $rem = $n % 2;
my $div = int($n / 2);
print $rem;
num2bin_reverse($div) if ($div > 0);
}

No comments:

Post a Comment

Followers

About Me

Torrance, CA, United States