2. Add Two Numbers

Medium

Problem:

Add the numbers in a linked list that are stored in reverse order.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807

https://leetcode.com/problems/add-two-numbers/arrow-up-right

What to learn:

Truth Table of Full Adder

The Sum and the decision for the next carry-over, Carry out, are determined by three inputs: input values A and B, and the previous carry-over, Carry in.

A
B
Carry in
Sum
Carry out

0

0

0

0

0

0

0

1

1

0

0

1

0

1

0

0

1

1

0

1

1

0

0

1

0

1

0

1

0

1

1

1

0

0

1

1

1

1

1

1

Solution:

Data type conversion

  1. Reverse the given linked lists

  2. Convert the linked list to integer.

  3. Add the numbers.

  4. Convert the sum to a string.

  5. Create a new linked list from the sum.

  6. Return the result linked list.

chevron-rightA little different code, but same logichashtag

What to learn from this code?

  • How to make a reversed linked list

  • How to convert a string list into a string

Full Adder

Original adders perform binary operations using logical circuits, but here we can implement it in a manner similar to a full adder of logical circuits using decimal operations.

We will solve it by referring only to the overall structure of the full adder, which takes the remainder as the operation result and raises the quotient in the form of a carry.

  1. l1, l2 play the same role as A, B in the figure above, performing operations on the two input values, and if the digits overflow as follows, a carry is set.

  2. If the addition result becomes two digits, the quotient is set as a carry to be used in the next operation, and the remainder is taken as the value.

Last updated