LeetCode Problem - Link
Today I attempted to solve the Add Two Numbers Problem on LeetCode, don't be fooled by the title. It's not as simple as adding two numbers. The devil is in the details. JK! It's not that difficult to be honest, although I did take a lot of time to understand some minor blockers I had faced while solving it. One was - what the hell does a ListNode mean? took me a while to understand that it's a simple LinkedList - a JavaScript object.
I didn't try to do any LinkedList magic as I was more interested in writing readable code, that's what I'm all about. I'll try to come back to it at a later point to see if I can find a quicker or a smarter way to approach this.
Linear/Sequential Approach
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function (l1, l2) { var num1 = getTraversedLLString(l1) var num2 = getTraversedLLString(l2) var sum = num1 + num2 + '' // typecast return buildLinkedListFromString(sum) }; var buildLinkedListFromString = (str) => { var linkedList = null; for (var i = 0; i < str.length; i++) { linkedList = { val: parseInt(str[i]), next: linkedList } } return linkedList } var getTraversedLLString = (linkedList) => { var curr = linkedList var str = '' while (curr !== null) { str += curr.val curr = curr.next; } var reversed = reverseString(str) return BigInt(reversed) } var reverseString = (str) => { var arr = [] for (var i = 0; i < str.length; i++) { arr.push(str[i]) } for (var i = 0; i < arr.length / 2; i++) { var temp = arr[i]; arr[i] = arr[arr.length - 1 - i] arr[arr.length - 1 - i] = temp } return arr.join('') }