tag:blogger.com,1999:blog-6314876008291942531.post6647696746282033931..comments2021-03-28T11:31:00.109-07:00Comments on Antonio Gulli's coding playground: Add two numbers representened in lists (with carry)Unknownnoreply@blogger.comBlogger3125tag:blogger.com,1999:blog-6314876008291942531.post-71693754310611876922010-06-09T18:13:36.458-07:002010-06-09T18:13:36.458-07:00There is another solution that shares the same tim...There is another solution that shares the same time and space characteristics as the one outlined above. The solution above requires the following from an implementation perspective:<br /><br />1. Walk thru' both lists to determine the shorter one O(m+n)<br />2. Insert elements into the shorter list to make them equal size O(n-m)<br />3. Walk the list to sum O(n).<br /><br />The solution I had was to simply reverse both the lists (amounts to 1 and 2 above). Simply walk the list and sum the numbers until you have hit the end of the largest list. <br /><br />Pseudo Code:<br /><br />firstList->reverseList();<br />secondList->reverseList();<br /><br />int sum = 0;<br />int i =1;<br /><br />Node* l1 = firstList->getHead();<br />Node* l2 = secondList->getHead();<br /><br />while (l1 && l2)<br />{<br /> int res = l1->getIntValue() + l2->getIntValue();<br /> sum = res*i + sum;<br /> i *= 10;<br /> l1 = l1->getNext();<br /> l2 = l2->getNext();<br />}<br /><br />//<br />// if the lists are of unequal sizes, walk the residual list using the same // algorithm above.<br />//Venkateshhttps://www.blogger.com/profile/15893132887136527161noreply@blogger.comtag:blogger.com,1999:blog-6314876008291942531.post-88718193777287633172010-04-13T00:38:27.841-07:002010-04-13T00:38:27.841-07:00One more point - we need to assume 0s in the short...One more point - we need to assume 0s in the shorter list to resize it to the length of longer one.Anonymoushttps://www.blogger.com/profile/03337365075523724707noreply@blogger.comtag:blogger.com,1999:blog-6314876008291942531.post-85386519070717449872010-02-06T09:22:05.470-08:002010-02-06T09:22:05.470-08:00This is a quite cute puzzle! It can be done in con...This is a quite cute puzzle! It can be done in constant space and linear time by "predicting" the carries. <br /><br />If I am summing two digits I can determine the current carry by looking at the next two digits: if they sum up to 10 or more then the carry is 1, if their sum is less than 9 then carry is 0. Finally, if their sum is<br />exactly 9, I go forward in both lists (recording the current position) and look for the first couple of digits whose sum is not 9, then propagate the carry backward.GiroTontihttps://www.blogger.com/profile/10692779656905527925noreply@blogger.com