2. Add Two Numbers
https://leetcode.com/problems/add-two-numbers/
Problem
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Strategy
So my strategy is to first base my solution on how I receive my input, and what output I should be generating. So knowing that my input is never going to be empty, I don't have to worry about that test case. As well as that, the input is always positive, which makes everything a lot easier. In addition, the number represented by the linked lists do not contain any leading zeroes - so no stripping will have to be done (but casting to an int would resolve this anyway).
So to strategise, I basically make a checklist of how I want to first process the input. The easiest way to generate the sum, is to convert the linked list inputs into numbers first (integers) and that allows me to sum them up very easily. From there, I can look into how I can convert the result of the addition to a linked list which I return.
Converting Input to a Number
So given the two inputs are of the form:
L1: (digit_0, digit_10, digit_100)
and L1: (digit_0, digit_10, digit_100)
What I need to do is as follows:
Once I've done this, I will have two list variables which contain the complete numbers in the correct order that correspond to L1 and L2.
Converting the Lists to Integers and doing the Math
At this stage, we have our lists where we want them; containing the digits of the number in order. Now all we need to do is convert them into a number and add for the desired result. This takes a bit of manipulation in the following steps, due to the restrictions of some of the functions.
After this, we will have a variable containing the sum of the two numbers that were given as inputs.
Obtaining the result as a Linked List and Returning
Finally, the last step of this problem is to take the result, split it up to digits and convert it to a linked list which we can return. Breaking this up, we have a checklist as such:
Solution
Putting all of this together, we can obtain a solution that looks like:
Better Solution
Given the inputs as they are, they are in optimal order for us to be able to calculate their sum just like we would on paper. In this case, we simply need something to store the carry, and thereby iteratively we calculate and append nodes to the linked list which we are returning.
Last updated
Was this helpful?