Addition of Two Numbers represented by Linked List nodes
I'm preparing for an interview. The question I got is: Two numbers are
represented by a linked list, where each node contains a single digit.The
digits are stored in reverse oder, such that the 1's digit is at the head
of the list. Write a function that adds the two numbers and returns the
sum as a linked list. The suggested answer adds each digits individually
and keeps a "carry" number. For example, if the first digits of the two
numbers are "5" and "7". The algorithm records "2" in the first digit of
resulting sum and keeps "1" as a "carry" to add to 10th digit of result.
However, my solution is to traverse the two linked lists and translate
them into two integers. Then I add the numbers and translate sum to a new
linked list. Wouldn't my solution be more straight forward and efficient?
Thanks!
No comments:
Post a Comment