Today I solved another leetcode problem. This one involved adding two numbers which are represented as two linked lists.
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Inital Stab
I went for a hacky method. I decided to process the linked lists into a list cast them to strings reverse it and created a linked list based on that list.
It works. But it wasn't pretty.
The Better Method
The trick here was to imagine that you are performing the addition as you would with pen and paper.
The idea is you can process each digit column wise:
As when we do it on pen and paper, we have to account for carry on. To do this we can just extract the last digit in the summation with:
And then if there is a carry we can extract that with:
note: carry can only either be 0 or 1, because the maximum that summation can be is 9 + 9 + 1
Armed with my new knowledge I decided to implement a similar solution but with arrays instead. You can check it out.
Array Solution
Contact
If you have any comments or thoughts you can reach me at any of the places below.