java - Addition of Two Numbers represented by Linked List nodes -
i'm preparing interview. question got is: 2 numbers represented linked list, each node contains single digit.the digits stored in reverse oder, such 1's digit @ head of list. write function adds 2 numbers , returns sum linked list. suggested answer adds each digits individually , keeps "carry" number. example, if first digits of 2 numbers "5" , "7". algorithm records "2" in first digit of resulting sum , keeps "1" "carry" add 10th digit of result. however, solution traverse 2 linked lists , translate them 2 integers. add numbers , translate sum new linked list. wouldn't solution more straight forward , efficient? thanks!
while solution may more straightforward, don't think it's more efficient.
i'm assuming "correct" algorithm this:
- pop first element of both lists
- add them (with carry if there one) , make new node using ones digit
- pass carry (dividing sum 10 actual thing carry) , repeat 1) , 2), each successive node being pointed previous one.
the main things see when i'm comparing algorithm 1 is:
- in terms of memory, want create 2
biginteger
s store intermediate values (i'm assuming you're usingbiginteger
or equivalentobject
avoid constraints ofint
orlong
), on top of final linked list itself. original algorithm doesn't use more couple ofint
s intermediate calculations, , in long run, original algorithm uses less memory. - you're suggesting of arithmetic using
biginteger
s, rather inint
s. although it's possiblebiginteger
optimized point isn't slower primitive operations, highly doubt callingbiginteger#add
faster doing+
operation onint
s.
also, more food thought. suppose didn't have handy biginteger
store arbitrarily large integers. you're going have have way store arbitrarily large integers algorithm work properly. after that, need way add arbitrarily large integers add arbitrarily large integers, , end problem either have original algorithm anyway, or end using different representation in subroutine (yikes).
Comments
Post a Comment