There are several solutions to your problem. They are all different ways of preprocessing your data so that it is in a suitable state for the main algorithm. Ultimately they use the facility of split with an empty string to generate a list of single characters. You can either provide your input data as a number in string, or convert your array to a string (using join most likely), then use split to create a clean list of digits:

my @number = split '', '1234567';

However with a little more preprocessing the actual addition logic becomes much simpler. Consider:

use strict; use warnings; my @numbers = map {[reverse split '']} qw(109156 114); my $maxDigits = 0; @$_ > $maxDigits and $maxDigits = @$_ for @numbers; @numbers = map {[@$_, (0) x ($maxDigits - @$_)]} @numbers; my @result; my $carry; for my $digit (0 .. $maxDigits - 1) { my $sum = $carry; $sum += $_->[$digit] for @numbers; push @result, substr $sum, -1, 1, ''; $carry = $sum || 0; } @numbers = map {[reverse @$_]} @numbers; @result = reverse @result; print "@$_\n" for @numbers; print '-' x ($maxDigits * 2), "\n"; print "@result\n";

Prints:

1 0 9 1 5 6 0 0 0 1 1 4 ------------ 1 0 9 2 7 0

Suppressing the leading zeros is left as an exercise for the reader. ;)


True laziness is hard work

In reply to Re: Arithmetical Simulation by GrandFather
in thread Arithmetical Simulation by biohisham

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.