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:

  1. pop first element of both lists
  2. add them (with carry if there one) , make new node using ones digit
  3. 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:

  1. in terms of memory, want create 2 bigintegers store intermediate values (i'm assuming you're using biginteger or equivalent object avoid constraints of int or long), on top of final linked list itself. original algorithm doesn't use more couple of ints intermediate calculations, , in long run, original algorithm uses less memory.
  2. you're suggesting of arithmetic using bigintegers, rather in ints. although it's possible biginteger optimized point isn't slower primitive operations, highly doubt calling biginteger#add faster doing + operation on ints.

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

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -